Advertisement
DulcetAirman

Predicate chaining

Jun 29th, 2019
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. package ch.claude_martin;
  2.  
  3. import java.util.Arrays;
  4. import java.util.List;
  5. import java.util.function.Predicate;
  6.  
  7. public final class SomeClass {
  8.   public static void main(String[] args) {
  9.     List<String> names = Arrays.asList("Albert", "Barbara", "Claude", "Danièle", "Eric", "Florence");
  10.     Predicate<String> p0 = s -> true;
  11.     Predicate<String> p1 = s -> true;
  12.     Predicate<String> p2 = s -> true;
  13.     Predicate<String> p3 = s -> true;
  14.     // You can just use add:
  15.     names.stream().allMatch(p0.and(p1).and(p2).and(p3));
  16.     // But you probably only have a list/set of predicates:
  17.     var predicates = List.of(p0, p1, p2, p3);
  18.     // You can reduce them to a single predicate.
  19.     // The identity must return true or you'd always get false.
  20.     var reduced = predicates.stream().reduce(s -> true, Predicate::and);
  21.     // But what if the list is actually empty? Maybe then you always want false.
  22.     var reduced2 = predicates.stream().reduce(Predicate::and).orElse(s -> false);
  23.     // And then just use it:
  24.     var allMatch = names.stream().allMatch(reduced);
  25.     System.out.println(allMatch);
  26.   }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement