10

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!

shmosel
  • 49,289
  • 6
  • 73
  • 138
Matley
  • 1,953
  • 4
  • 35
  • 73

2 Answers2

17

You can stream and reduce them like this:

Predicate<TaskFx> predicate = predicates.stream()
        .reduce(x -> true, Predicate::and);
shmosel
  • 49,289
  • 6
  • 73
  • 138
  • 15
    I prefer `.reduce(Predicate::and).orElse(x -> true);` as it avoids an obsolete combining of an always `true` predicate with an existing predicate. – Holger Nov 22 '17 at 10:26
3

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());
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126