[Solved] Method Reference of Java


Consider the following example using toUpperCase which is also an instance method.

It works in this case because the Stream item that is being handled is of the same type as the class of the method being invoked. So the item actually invokes the method directly.

So for

Stream.of("abcde").map(String::toUpperCase).forEach(System.out::println);

the String::toUpperCase call will be the same as "abcde".toUpperCase()

If you did something like this:

Stream.of("abcde").map(OtherClass::toUpperCase).forEach(System.out::println);

“abcde” is not a type of OtherClass so the OtherClass would need to look like the following for the stream to work.

class OtherClass {
    public static String toUpperCase(String s) {
       return s.toUpperCase();
    }
} 

solved Method Reference of Java