How can I apply multiple predicates to a java.util.Stream\'s filter() method?
This is what I do now, but I don\'t really like it. I have a
I've managed to solve such a problem, if a user wants to apply a list of predicates in one filter operation, a list which can be dynamic and not given, that should be reduced into one predicate - like this:
public class TestPredicates {
public static void main(String[] args) {
List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println(numbers.stream()
.filter(combineFilters(x -> x > 2, x -> x < 9, x -> x % 2 == 1))
.collect(Collectors.toList()));
}
public static Predicate combineFilters(Predicate... predicates) {
Predicate p = Stream.of(predicates).reduce(x -> true, Predicate::and);
return p;
}
}
Note that this will combine them with an "AND" logic operator. To combine with an "OR" the reduce line should be:
Predicate p = Stream.of(predicates).reduce(x -> false, Predicate::or);