FazoM FazoM - 6 months ago 22
Java Question

Java 8 - filter collection using many filters

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 = .....

Answer
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());
Comments