技术编程5万字:Stream和Lambda表达式最佳实践2( 八 )


Predicate虽然是一个interface , 但是它有几个默认的方法可以用来实现Predicate之间的组合操作 。
比如:Predicate.and(), Predicate.or(), 和 Predicate.negate() 。
下面看下他们的例子:@Testpublic void combiningPredicate(){Predicate
predicate1 = s -> s.startsWith("a");Predicate
predicate2 =s -> s.length() > 1;List
stringList1 = Stream.of("a","ab","aac","ad").filter(predicate1.and(predicate2)).collect(Collectors.toList());log.info("{}",stringList1);List
stringList2 = Stream.of("a","ab","aac","ad").filter(predicate1.or(predicate2)).collect(Collectors.toList());log.info("{}",stringList2);List
stringList3 = Stream.of("a","ab","aac","ad").filter(predicate1.or(predicate2.negate())).collect(Collectors.toList());log.info("{}",stringList3);}复制代码
实际上 , 我们并不需要显示的assign一个predicate , 只要是满足 predicate接口的lambda表达式都可以看做是一个predicate 。 同样可以调用and , or和negate操作:List
stringList4 = Stream.of("a","ab","aac","ad").filter(((Predicate
)a -> a.startsWith("a")).and(a -> a.length() > 1)).collect(Collectors.toList());log.info("{}",stringList4);复制代码14.5 Predicate的集合操作
如果我们有一个Predicate集合 , 我们可以使用reduce方法来对其进行合并运算:@Testpublic void combiningPredicateCollection(){List
> allPredicates = new ArrayList
a.startsWith("a"));allPredicates.add(a -> a.length() > 1);List
stringList = Stream.of("a","ab","aac","ad").filter(allPredicates.stream().reduce(x->true, Predicate::and)).collect(Collectors.toList());log.info("{}",stringList);}复制代码
上面的例子中 , 我们调用reduce方法 , 对集合中的Predicate进行了and操作 。 15. 中构建无限的stream
在java中 , 我们可以将特定的集合转换成为stream , 那么在有些情况下 , 比如测试环境中 , 我们需要构造一定数量元素的stream , 需要怎么处理呢?
这里我们可以构建一个无限的stream , 然后调用limit方法来限定返回的数目 。 15.1 基本使用
先看一个使用Stream.iterate来创建无限Stream的例子:@Testpublic void infiniteStream(){Stream
infiniteStream = Stream.iterate(0, i -> i + 1);List
collect = infiniteStream.limit(10).collect(Collectors.toList());log.info("{}",collect);}复制代码
上面的例子中 , 我们通过调用Stream.iterate方法 , 创建了一个0 , 1 , 2 , 3 , 4....的无限stream 。
然后调用limit(10)来获取其中的前10个 。 最后调用collect方法将其转换成为一个集合 。
看下输出结果:INFO com.flydean.InfiniteStreamUsage - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]复制代码15.2 自定义类型
如果我们想输出自定义类型的集合 , 该怎么处理呢?
首先 , 我们定义一个自定义类型:@Data@AllArgsConstructorpublic class IntegerWrapper {private Integer integer;}复制代码
然后利用Stream.generate的生成器来创建这个自定义类型:public static IntegerWrapper generateCustType(){return new IntegerWrapper(new Random().nextInt(100));}@Testpublic void infiniteCustType(){Supplier
randomCustTypeSupplier = InfiniteStreamUsage::generateCustType;Stream
infiniteStreamOfCustType = Stream.generate(randomCustTypeSupplier);List
collect = infiniteStreamOfCustType.skip(10).limit(10).collect(Collectors.toList());log.info("{}",collect);}复制代码


推荐阅读