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
0 B
|👍
/👎