fork download
  1. import java.util.Arrays;
  2. import java.util.Objects;
  3. import java.util.function.BinaryOperator;
  4. import java.util.function.Function;
  5. import java.util.function.Predicate;
  6. import java.util.stream.Stream;
  7.  
  8. class PredicateExample {
  9. public static void main(String[] args) {
  10. Stream<Animal> greenAnimals = Stream.<Animal>of()
  11. .filter(
  12. MultiPred.ofOr(Animal::getColor, Color.WHITE::equals, Color.GREEN::equals)
  13. .or(
  14. MultiPred.of(Animal::getType, AnimalType.CARNIVORE::equals)
  15. .and(Animal::canFly) // we can chain custom Predicates with regular ones
  16. )
  17. .or(
  18. MultiPred.of(Animal::getType, AnimalType.HERBIVORE::equals)
  19. .and(MultiPred.of(Animal::getColor, Color.PURPLE::equals)
  20. .or(Animal::canSwim)
  21. )
  22. )
  23. );
  24. System.out.println("No errors");
  25. }
  26. }
  27. class MultiPred {
  28. @SafeVarargs
  29. public static <T, K> Predicate<T> ofAnd(Function<T, K> keyExtractor,
  30. Predicate<K>... predicates) {
  31.  
  32. return of(keyExtractor, k -> true, Predicate::and, predicates);
  33. }
  34.  
  35. @SafeVarargs
  36. public static <T, K> Predicate<T> ofOr(Function<T, K> keyExtractor,
  37. Predicate<K>... predicates) {
  38.  
  39. return of(keyExtractor, k -> false, Predicate::or, predicates);
  40. }
  41.  
  42. @SafeVarargs
  43. public static <T, K> Predicate<T> of(Function<T, K> keyExtractor,
  44. Predicate<K> identity,
  45. BinaryOperator<Predicate<K>> op,
  46. Predicate<K>... predicates) {
  47.  
  48. Objects.requireNonNull(predicates);
  49.  
  50. Predicate<K> predicate = Arrays.stream(predicates).reduce(identity, op);
  51.  
  52. return of(keyExtractor, predicate);
  53. }
  54.  
  55. public static <T, K> Predicate<T> of(Function<T, K> keyExtractor,
  56. Predicate<K> predicate) {
  57.  
  58. Objects.requireNonNull(keyExtractor);
  59. Objects.requireNonNull(predicate);
  60.  
  61. return t -> predicate.test(keyExtractor.apply(t));
  62. }
  63. }
  64. enum Color { WHITE, GREEN, PURPLE }
  65. enum AnimalType { HERBIVORE, CARNIVORE }
  66. class Animal {
  67. final AnimalType type;
  68. final Color color;
  69. final boolean canSwim, canFly;
  70.  
  71. Animal(AnimalType type, Color color, boolean canSwim, boolean canFly) {
  72. this.type = type;
  73. this.color = color;
  74. this.canSwim = canSwim;
  75. this.canFly = canFly;
  76. }
  77. public AnimalType getType() { return type; }
  78. public Color getColor() { return color; }
  79. public boolean canSwim() { return canSwim; }
  80. public boolean canFly() { return canFly; }
  81. }
  82.  
Success #stdin #stdout 0.11s 48488KB
stdin
Standard input is empty
stdout
No errors