Short-circuiting(短路),顾名思义,在流操作中如果满足一些条件那么整个流就被短路了,不至于将流中的所有元素都流过流处理function中,揍像我们在for循环中使用的break一样;

短路操作有

  • anyMatch
  • allMatch
  • noneMatch
  • findFirst
  • findAny
  • limit

infinite stream

  1. @Test
  2. public void generate () {
  3. System.out.println(IntStream.generate(() -> (int) (Math.random() * 100)).peek(System.out::println).anyMatch((i) -> i == 6));
  4. }

在上面的infinite stream中如果使用anyMatch第一个元素若不匹配会直接返回false,终止流。
anyMatch及noneMatch如果没达到条件流会一直处于活跃状态。
findFirst及findAny会直接返回第一个element的Optional对象。
limit当stream到达limit时直接返回一个子流。

finite stream

代码:

  1. List< String > names = Arrays.asList("barry", "andy", "ben", "chris", "bill");
  2. Stream < String > namesStream =
  3. names.stream().map(n -> {
  4. System.out.println("In map - " + n);
  5. return n.toUpperCase();
  6. }).filter(upperName -> {
  7. System.out.println("In filter - " + upperName);
  8. return upperName.startsWith("B");
  9. }).limit(3);
  10. namesStream.collect(Collectors.toList()).forEach(System.out::println);

虚区:

  1. In map - barry
  2. In filter - BARRY
  3. In map - andy
  4. In filter - ANDY
  5. In map - ben
  6. In filter - BEN
  7. In map - chris
  8. In filter - CHRIS
  9. In map - bill
  10. In filter - BILL
  11. BARRY
  12. BEN
  13. BILL