簡體   English   中英

如何從Java的自定義謂詞列表中創建謂詞?

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

我對編程比較陌生,過去兩天我一直想知道如何制作一個由其他Predicates自定義列表組成的謂詞。 所以我想出了一些解決方案。 下面是一個代碼片段,可以給你一個想法。 因為我是基於單獨閱讀各種文檔而編寫的,所以我有兩個問題:1 /它是一個很好的解決方案嗎? 2 /是否有其他一些推薦的解決方案可以解決這個問題?

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));

  }
}

您可以使用靜態方法接收許多謂詞並返回所需的謂詞:

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

一個變種:

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

這里我使用的是Stream.reduce ,它將標識和運算符作為參數。 Stream.reducePredicate::and運算符應用於流的所有元素以生成結果謂詞,並使用標識對流的第一個元素進行操作。 這就是我使用t -> true作為標識的原因,否則結果謂詞最終可能會被評估為false

用法:

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

Java Predicate有一個很好的AND函數,它返回新謂詞,它是兩個謂詞的評估。 您可以將它們全部添加到一個中。

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

例如:

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 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM