Short-circuiting(短路),顾名思义,在流操作中如果满足一些条件那么整个流就被短路了,不至于将流中的所有元素都流过流处理function中,揍像我们在for循环中使用的break一样;
短路操作有
- anyMatch
- allMatch
- noneMatch
- findFirst
- findAny
- limit
infinite stream
@Testpublic void generate () {System.out.println(IntStream.generate(() -> (int) (Math.random() * 100)).peek(System.out::println).anyMatch((i) -> i == 6));}
在上面的infinite stream中如果使用anyMatch第一个元素若不匹配会直接返回false,终止流。
anyMatch及noneMatch如果没达到条件流会一直处于活跃状态。
findFirst及findAny会直接返回第一个element的Optional对象。
limit当stream到达limit时直接返回一个子流。
finite stream
代码:
List< String > names = Arrays.asList("barry", "andy", "ben", "chris", "bill");Stream < String > namesStream =names.stream().map(n -> {System.out.println("In map - " + n);return n.toUpperCase();}).filter(upperName -> {System.out.println("In filter - " + upperName);return upperName.startsWith("B");}).limit(3);namesStream.collect(Collectors.toList()).forEach(System.out::println);
虚区:
In map - barryIn filter - BARRYIn map - andyIn filter - ANDYIn map - benIn filter - BENIn map - chrisIn filter - CHRISIn map - billIn filter - BILLBARRYBENBILL
