简体   繁体   中英

How to make a Predicate from a custom list of Predicates in Java?

I'm relatively new to programming and I have been wondering for past two days how to make a Predicate that is made from a custom list of other Predicates. So I've came up with some kind of solution. Below is a code snippet that should give you an idea. Because I have written it based on solely reading various pieces of documentations I have two questions: 1/ is it a good solution? 2/ is there some 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));

  }
}

You could 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));
}

A variant:

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'm using Stream.reduce , which takes the identity and an operator as arguments. Stream.reduce applies the Predicate::and operator to all elements of the stream to produce a result predicate, and uses the identity to operate on the first element of the stream. This is why I have used t -> true as the identity, otherwise the result predicate might end up evaluating to false .

Usage:

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

Java Predicate has a nice function of AND which returns new Predicate which is evaluation of both predicates. You can add them all into 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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM