Home > Mobile >  How can I use a Predicate in Java?
How can I use a Predicate in Java?

Time:05-29

How can I use the following Predicate?

Predicate<Integer> isOdd = n -> n % 2 != 0;

My try:

System.out.println(isOdd(5));

Compiler output:

java: cannot find symbol
symbol:   method isOdd(int)
location: class Main

CodePudding user response:

To invoke a Predicate, use the method called test.

System.out.println(isOdd.test(5));

or

if(isOdd.test(5)){
  // Do something fun
}

This is documented here

CodePudding user response:

Predicate<T> is an interface, so you need to explicitly call the method declared in it, i.e. test(T t); even if the variable captured a lambda:

isOdd.test(5)
  • Related