java – How to apply multiple predicates to Java.util.Stream?

I was able to solve such a problem, if a user wants to apply a list of predicates in a filter operation, a list that can be dynamic and not supplied, which should be reduced to a predicate, like this:

public class TestPredicates {
    public static void main(String[] args) {
        List<Integer> 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 <T> Predicate<T> combineFilters(Predicate<T>... predicates) {

        Predicate<T> p = Stream.of(predicates).reduce(x -> true, Predicate::and);
        return p;

    }
}

Note that this will combine them with a logical “AND” operator. To combine with an “OR” the reduction line should be:

Predicate<T> p = Stream.of(predicates).reduce(x -> false, Predicate::or);

Leave a comment