DulcetAirman icon

Predicate chaining

DulcetAirman | PRO | 06/29/19 09:40:36 PM UTC | 0 ⭐ | 618 👁️ | Never ⏰ | []
Java |

1.11 KB

|

None

|

0 👍

/

0 👎

package ch.claude_martin;
 
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
 
public final class SomeClass {
  public static void main(String[] args) {
    List<String> names = Arrays.asList("Albert", "Barbara", "Claude", "Danièle", "Eric", "Florence");
    Predicate<String> p0 = s -> true;
    Predicate<String> p1 = s -> true;
    Predicate<String> p2 = s -> true;
    Predicate<String> p3 = s -> true;
    // You can just use add:
    names.stream().allMatch(p0.and(p1).and(p2).and(p3));
    // But you probably only have a list/set of predicates:
    var predicates = List.of(p0, p1, p2, p3);
    // You can reduce them to a single predicate. 
    // The identity must return true or you'd always get false.
    var reduced = predicates.stream().reduce(s -> true, Predicate::and);
    // But what if the list is actually empty? Maybe then you always want false.
    var reduced2 = predicates.stream().reduce(Predicate::and).orElse(s -> false);
    // And then just use it:
    var allMatch = names.stream().allMatch(reduced);
    System.out.println(allMatch);
  }
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎