Skip to content
Advertisement

Java – How do I create Predicates as Arrays.asList() arguments?

I have a few predicates that I want to put in a list so I can then call stream().noneMatch() on my list. I successfully did this by creating named Predicates but how can I create them within an Arrays.asList()’s argument list?

Here’s the working code that I’d like to convert:

ArrayList<Predicate<MyClass>> checks = new ArrayList<>();
Predicate<MyClass> isCond1 = myClassHelper::isCond1;
Predicate<MyClass> isCond2 = myClassHelper::isCond2;
checks.add(isCond1);
checks.add(isCond2);

I’d expect the result of the conversion to look something like this:

List<Predicate> checks = Arrays.asList(myClassHelper::isCond1, myClassHelper::isCond2);

or

List<Predicate> checks = Arrays.asList(a -> myClassHelper::isCond1, a -> myClassHelper::isCond2);

(neither of these are correct)
Where can I specify the argument for the conditions here?

Sorry if this could have been titled better, I always struggle with that.

Answer

The first statement should work but you forgot to specify the predicate type Predicate<MyClass>, otherwise the compiler cannot infer it from the method references:

List<Predicate<MyClass>> checks2 = Arrays.asList(myClassHelper::isCond1, myClassHelper::isCond2);

Or using lambdas:

List<Predicate<MyClass>> checks3 = Arrays.asList(a -> myClassHelper.isCond1(a), a -> myClassHelper.isCond2(a));
Advertisement