Matelutex
Matelutex

Reputation: 2210

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!

Upvotes: 11

Views: 6011

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56423

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

Upvotes: 4

shmosel
shmosel

Reputation: 50716

You can stream and reduce them like this:

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

Upvotes: 19

Related Questions