当在
Java 8 lambda表达式中使用filter(Predicate<?super T>谓词)调用时,我有两个想法是关于是否将所有Predicate逻辑放在一个调用中,还是链式过滤器(Predicate<?super T>谓词)在适当情况下呼吁提供可读性.
我认为链接过滤器(Predicate<?super T>谓词)调用会很便宜,因为它们还没有遇到终结符,所以在可读性方面会犯错,但我对Streams API的知识不够自信完全明白什么是权衡取舍.
借助以下示例(考虑更复杂的谓词),哪种实现更优越:List< Person> usingOneFilter或List< Person> usingTwoFilters?
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class SEExample { private static class Person { private final int age; private final int heightInCm; public Person(int age,int heightInCm) { this.age = age; this.heightInCm = heightInCm; } public int getAge() { return age; } public int getHeight() { return heightInCm; } } public static void main(String[] args) { List<Person> people = Arrays.asList( new Person(14,140),new Person(15,new Person(16,150),new Person(17,120)); List<Person> usingOneFilter = people .stream() .filter(p -> p.getAge() >= 16 && p.getHeight() >= 130) .collect(Collectors.toList()); List<Person> usingTwoFilters = people .stream() .filter(p -> p.getAge() >= 16) .filter(p -> p.getHeight() >= 130) .collect(Collectors.toList()); } }