Java how to compare Predicates
I have two prodicates :
Predicate<CategoryModel> predicate1 = NavigationCategoryModel.class::isInstance; Predicate<CategoryModel> predicate2 = BrandCategoryModel.class::isInstance;
With and if statement , how can I identify which predicate am I using ? I’m trying to do something like this but obviously isn’t compiling :
if(predicate1.equals(NavigationCategoryModel.class::isInstance)){ } if(predicate1==NavigationCategoryModel.class::isInstance){ }
Any hint ? I’m quite new to Java 8 lambdas
This is the code of the Pojos (simple inheritance for test purposes):
public class CategoryModel { } public class NavigationCategoryModel extends CategoryModel{ } public class BrandCategoryModel extends CategoryModel { }
You should use test
method on Predicates. And, you’ve to provide the object to perform validation instead of actual method reference
predicate.test(object)
Documentation: Predicate#test
For your problem, you can test if predicate1 returns true when object is of type NavigationCategoryModel
as below:
predicate1.test(new NavigationCategoryModel()) // returns true
Similarly, for BrandCategoryModel
, use:
predicate2.test(new BrandCategoryModel()) // returns true
If you want to test that object matches either of two, you can combine both the predicates like:
predicate1.or(predicate2).test(new NavigationCategoryModel()) // returns true predicate1.or(predicate2).test(new BrandCategoryModel()) // returns true
What you try is to find which implementation you use.
The only way is to use function test
from Predicate
.
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()); }
Just like KunLun’s solution, but I think you should add one more condition, for example
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()));