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 am assuming your Filter is a type distinct from java.util.function.Predicate, which means it needs to be adapted to it. One approach which will work goes like this:
things.stream().filter(t -> filtersCollection.stream().anyMatch(f -> f.test(t)));
This incurs a slight performance hit of recreating the filter stream for each predicate evaluation. To avoid that you could wrap each filter into a Predicate and compose them:
things.stream().filter(filtersCollection.stream().map(f -> f::test)
.reduce(Predicate::or).orElse(t->false));
However, since now each filter is behind its own Predicate, introducing one more level of indirection, it is not clear-cut which approach would have better overall performance.
Without the adapting concern (if your Filter happens to be a Predicate) the problem statement becomes much simpler and the second approach clearly wins out:
things.stream().filter(
filtersCollection.stream().reduce(Predicate::or).orElse(t->true)
);