user153245
user153245

Reputation: 287

How can I use a Predicate in Java?

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

Upvotes: 1

Views: 1127

Answers (2)

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36391

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)

Upvotes: 2

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79828

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

Upvotes: 8

Related Questions