java8,java.util.function中 Function, Supplier, Consumer, Predicate和其他函数式接口广泛用在支持lambda表达式的API中,以此可以缩短lambda的长度和提高代码可阅读性。当然普通代码片段种用它来作为筛选条件也可以。
Predicate能为我们做些什么事儿呢?下面以数据赛选为例。
List<Person> personList= Stream.of(
new Person(21,"zhangsan"),
new Person(22,"leftso"),
new Person(23,"wangwu"),
new Person(24,"wangwu"),
new Person(25,"leftso"),
new Person(26,"zhangsan")
).collect(Collectors.toList());
代码实现:
Predicate<Person> personPredicate = x -> x.getAge() > 22;
Long count=personList.stream().filter(personPredicate).count();
System.out.println(count);
简述:第一步编写过滤条件personPredicate,第二部带入stream中进行过滤。
咋一看这是个“或”关系的赛选,代码实现为:
Predicate<Person> personPredicate = x -> x.getAge() > 22;
personPredicate.or(x->"leftso".equals(x.getName()));
long count=personList.stream().filter(personPredicate).count();
System.out.println(count);
https://www.leftso.com/article/718.html