How do I make a Predicate from a custom Predicates list in Java?

I am relatively new to programming and I have been interested in learning the last two days how to make a predicate created from a custom list of other predicates. So I came up with some kind of solution. Below is a piece of code that should give you an idea. Since I wrote this based solely on reading various documents, I have two questions: 1 / is this a good solution? 2 / is there any other recommended solution for this problem?

public class Tester {
  private static ArrayList<Predicate<String>> testerList;

  //some Predicates of type String here...

  public static void addPredicate(Predicate<String> newPredicate) {
    if (testerList == null) 
                 {testerList = new ArrayList<Predicate<String>>();}
    testerList.add(newPredicate);
  }

  public static Predicate<String> customTesters () {
    return s -> testerList.stream().allMatch(t -> t.test(s));

  }
}

      

+3


source to share


2 answers


You can have a static method that receives many predicates and returns the predicate you want:

public static <T> Predicate<T> and(Predicate<T>... predicates) {
    // TODO Handle case when argument is null or empty or has only one element
    return s -> Arrays.stream(predicates).allMatch(t -> t.test(s));
}

      

Option:

public static <T> Predicate<T> and(Predicate<T>... predicates) {
    // TODO Handle case when argument is null or empty or has only one element
    return Arrays.stream(predicates).reduce(t -> true, Predicate::and);
}

      



Here I am using Stream.reduce

which takes an ID and an operator as arguments. Stream.reduce

applies the operator Predicate::and

to all elements of the stream to create a result predicate and uses the identifier to work with the first element in the stream. This is why I used t -> true

as an identifier, otherwise the result predicate might end up evaluating false

.

Using:

Predicate<String> predicate = and(s -> s.startsWith("a"), s -> s.length() > 4);

      

+5


source


Java Predicate has a nice AND function that returns a new Predicate that evaluates both predicates. You can add them all in one with this.

https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html#and-java.util.function.Predicate-



example:

Predicate<String> a = str -> str != null;
Predicate<String> b = str -> str.length() != 0;
Predicate<String> c = a.and(b);

c.test("Str");
//stupid test but you see the idea :)

      

+1


source







All Articles