How to combine all predicates from the list <Predicate <MyClass>>

I have one problem, and I'm sure you will help me with my wrinkle.

I have

List<Predicate<TaskFx>> predicates

and I want to use these predicates in

taskFxList.stream().filter(predicates).collect(Collectors.toList());

as one predicate combined as:

predicate1.and(predicate2).and...

I have a table (13 columns) with some results (in JavaFx) and 6 fields for finding values ​​from these fields in this table. I can enter, for example, the values ​​in only 3 fields, so my

predicates.size() = 3;

The question is how best to prepare dynamically one

Predicate<TaskFx> predicate

consisting of all the predicates added by x.and (y) .and (z)

Many thanks for your help!

+4
source share
2 answers

You can broadcast reducethem as follows:

Predicate<TaskFx> predicate = predicates.stream()
        .reduce(x -> true, Predicate::and);
+7
source

Alternatively, you can simply process them as follows:

List<TaskFx> resultSet = stringList.stream()
                                   .filter(e -> predicates.stream().allMatch(x -> x.test(e)))
                                   .collect(Collectors.toList());
+3
source

Source: https://habr.com/ru/post/1689651/


All Articles