When using filter(Predicate<? super T> predicate)
calls in Java 8 lambda expressions, I'm in two minds about whether to put all the Predicate
logic in one call, or to chain filter(Predicate<? super T> predicate)
calls to aid readability where appropriate.
I presume that chaining filter(Predicate<? super T> predicate)
calls will be inexpensive since they have not yet met a terminator, so would err on the side of readability but I'm not confident enough in my knowledge of the Streams
API to fully understand what the trade-offs are.
With the aid of the following example (consider too more complex predicates), which implementation is superior: List<Person> usingOneFilter
or 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, 140),
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());
}
}
In such a small example I think readability isn't really compromised, but I still prefer using separate filter methods. Certainly if it's any more complex.
This is indeed not very expensive. There's no reason to "optimize" it unless you have a performance issue and profiling reveals that this is the bottleneck. But that's extremely unlikely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With