2

I would like to filter out my collection using multiple filters.

Let's assume I have a list of Strings and a function filter() to filter out empty Strings.

List<String> myList = .......

Typically, I would use streams like this:

myList.stream()
        .filter(elem -> filterOut(elem))
        .collect(Collectors.toList());

How to apply multiple filters from a collection (List or Set) using streams?

Set<Predicate> myFilters = .....
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
FazoM
  • 4,777
  • 6
  • 43
  • 61

2 Answers2

3
myList.stream()
        .filter(s -> myFilters.stream().allMatch(p -> p.test(s)))
        .collect(Collectors.toList());

Or if you're a fan of Guava:

com.google.common.base.Predicate<String> combined = Predicates.and(Iterables.transform(myFilters, p -> p::test));
myList.stream()
        .filter(combined::apply)
        .collect(Collectors.toList());
shmosel
  • 49,289
  • 6
  • 73
  • 138
2
Predicate combinedPredicate = myFilters.stream().reduce(Predicate::or).orElse(t -> false);
Nikem
  • 5,716
  • 3
  • 32
  • 59