
[英]How to compare Two List of Map to identify the matching and non matching records with multiple filter predicates in Java8 Streams
[英]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.