Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine all predicates from List<Predicate<MyClass>>

I have one problem and I'm sure you 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 a one predicate merged like:

predicate1.and(predicate2).and...

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

predicates.size() = 3;

The question is how best to prepare dynamically one

Predicate<TaskFx> predicate

consisting all predicates merged by x.and(y).and(z)

Thank you very much for your help!

like image 216
Matley Avatar asked Nov 21 '17 23:11

Matley


2 Answers

You can stream and reduce them like this:

Predicate<TaskFx> predicate = predicates.stream()
        .reduce(x -> true, Predicate::and);
like image 124
shmosel Avatar answered Sep 28 '22 18:09

shmosel


Alternatively you could just process them like this:

List<TaskFx> resultSet = stringList.stream()
                                   .filter(e -> predicates.stream().allMatch(x -> x.test(e)))
                                   .collect(Collectors.toList());
like image 30
Ousmane D. Avatar answered Sep 28 '22 19:09

Ousmane D.