Skip to content
Advertisement

Multiple filters applied to a single list in Java 8+

How can be achieved to pass a “list of filters” to a stream in Java 8, instead of applying them individually as illustrated in the following example?

https://howtodoinjava.com/java8/stream-multiple-filters-example/

The purpose would be to dynamically create a list of filters, one way would be to iterate through a list of filters and apply it to the list to be filtered.

Any other idea?

UPDATE:

Thanks for the comment of the predicate:

   final Predicate<?> predicate = new Predicate<?>() {

        @Override 
        public boolean test(Object object) {
            return false; //TODO: Implement first predicate
        }
    } ;

    predicate.and(...); //Implement another predicate.

Regards

~M

Advertisement

Answer

You can chain predicates with either the and or or operator. Do you want your combined predicate to be a predicate that matches objects that match all the component predicates, or just at least one of them? If you want to simulate a chain of filter calls:

someStream.filter(...)
            .filter(...)
            .filter(...)
            .filter(...)

Then you should use and.

Depending on what you choose, you can use either of these methods:

public static <T> Predicate<T> combineFilters(List<Predicate<T>> filters) {
    return filters.stream().reduce(Predicate::and).orElse(x -> true);
}

public static <T> Predicate<T> combineFilters(List<Predicate<T>> filters) {
    return filters.stream().reduce(Predicate::or).orElse(x -> false);
}

Usage:

someStream.filter(combineFilters(aListOfFilters))
    ...
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement