簡體   English   中英

Java 如何比較謂詞

[英]Java how to compare Predicates

我有兩個prodicates:

Predicate<CategoryModel> predicate1 = NavigationCategoryModel.class::isInstance;
Predicate<CategoryModel> predicate2 = BrandCategoryModel.class::isInstance;

使用 and if 語句,我如何識別我使用的是哪個謂詞? 我正在嘗試做這樣的事情,但顯然沒有編譯:

if(predicate1.equals(NavigationCategoryModel.class::isInstance)){
}

if(predicate1==NavigationCategoryModel.class::isInstance){
}

有什么提示嗎? 我對 Java 8 lambdas 很陌生

這是 Pojos 的代碼(簡單的 inheritance 用於測試目的):

public class CategoryModel {
}

public class NavigationCategoryModel  extends CategoryModel{
}

public class BrandCategoryModel extends CategoryModel {
}

您應該對謂詞使用test方法。 而且,您必須提供 object 來執行驗證,而不是提供實際的方法參考

predicate.test(object)

文檔: 謂詞#test

對於您的問題,您可以測試當 object 的類型為NavigationCategoryModel時 predicate1 是否返回 true,如下所示:

predicate1.test(new NavigationCategoryModel()) // returns true

同樣,對於BrandCategoryModel ,使用:

predicate2.test(new BrandCategoryModel()) // returns true

如果您想測試 object 是否匹配兩個中的任何一個,您可以組合兩個謂詞,例如:

predicate1.or(predicate2).test(new NavigationCategoryModel()) // returns true
predicate1.or(predicate2).test(new BrandCategoryModel()) // returns true

您嘗試的是找到您使用的實現。

唯一的方法是使用Predicate中的 function test

true if the input argument matches the predicate, otherwise false
public static void main(String args[]) {

    Predicate<CategoryModel> predicate1 = NavigationCategoryModel.class::isInstance;
    Predicate<CategoryModel> predicate2 = BrandCategoryModel.class::isInstance;

    System.out.println("Predicate1 isNavigation: " + isNavigation(predicate1));
    System.out.println("Predicate1 isBrand: " + isBrand(predicate1));
    System.out.println("--------------------------------------------------");
    System.out.println("Predicate2 isNavigation: " + isNavigation(predicate2));
    System.out.println("Predicate2 isBrand: " + isBrand(predicate2));

}

public static boolean isNavigation(Predicate<CategoryModel> predicate){

    return predicate.test(new NavigationCategoryModel());

}

public static boolean isBrand(Predicate<CategoryModel> predicate){

    return predicate.test(new BrandCategoryModel());

}

就像昆侖的解決方案一樣,但我認為您應該再添加一個條件,例如

Predicate<CategoryModel> predicate1 = NavigationCategoryModel.class::isInstance;
Predicate<CategoryModel> predicate2 = BrandCategoryModel.class::isInstance;

Predicate<CategoryModel> predicate1Testing = NavigationCategoryModel.class::isInstance;

System.out.println("Is A NavigationCategoryModel Predicate? " + predicate1.and(predicate1Testing).test(new NavigationCategoryModel()));

暫無
暫無

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

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