Java – How do I implement a method reference as a predicate?

How do I implement a method reference as a predicate?… here is a solution to the problem.

How do I implement a method reference as a predicate?

I’m new to java8 and I’m trying to understand this code. Here is a piece of code:

Stream.of("A", "B", "C").anyMatch(someObj.getStringValue()::equalsIgnoreCase)

someObj.getStringValue() references some objects, and getStringValue() returns some string values.

What is the equivalent predicate passed to the method reference of anyMatch(...)?

My understanding is that this is equivalent to:

Predicate<String> p = new Predicate<String>() {
    @Override
    public boolean test(String t) {
        return someObject.getStringValue().equalsIgnoreCase(t);
    }
}
Stream.of("A", "B", "C").anyMatch(p)

With this, I get the error “The local variable someObject defined in the closed scope must be final or actually final.” “Any explanation of this is appreciated.

Solution

The someObj.getStringValue() expression is evaluated externally, so the code equivalent is:

final String x = someObject.getStringValue();
Predicate<String> p = new Predicate<String>() {
    @Override
    public boolean test(String t) {
        return x.equalsIgnoreCase(t);
    }
}
Stream.of("A", "B", "C").anyMatch(p)

where the local variable x is also “anonymous”.

Therefore, someObject does not need to end efficiently.

You can verify this behavior of lambda expressions in the debugger by placing a breakpoint in getStringValue(). Even if the test() method is called 3 times (because the stream has 3 elements and assumes no match), the getStringValue() method will only be called once.

Related Problems and Solutions