Can be replaced with method reference using reflection in java

Motomine picture Motomine · Apr 10, 2017 · Viewed 11.9k times · Source

I have this code in intellij:

 return collection.stream().anyMatch(annotation -> 
                        method.isAnnotationPresent(annotation));

And the compiler tells me that "method.isAnnotationPresent(annotation)" can be replaced with method reference and I can't figure out how to do it because it has an argument.

Does anyone know how to make that?

Answer

developer picture developer · Apr 10, 2017

You can replace your code to use the method reference (look here) as shown below:

return collection.stream().anyMatch(method::isAnnotationPresent);

Basically, you are providing the isAnnotationPresent() method definition to the Lambda expression (of anyMatch method which accepts for Predicate) and the value from the stream will automatically be passed as an argument to the anyMatch method.