I have been using Java 8 method references for quite some time, but i have this question in my mind.
i know that method references is a short hand notation for a lambda expression,which calls a single method (the method may be a static one or a constructor or method belonging to a instance object).
does this mean, method references can used only as a substitute for lambda of consumer functional interfaces?
For example
Consumer<String> c = s -> System.out.println(s);
can be rewritten as
Consumer<String> c = System.out::println;
And
Consumer<T> c=(args) -> Class.staticMethod(args)
can be re written as
Class::staticMethod
Well it can for sure be written like that, this is close to the same thing under the hood. With a method reference, you are saving internally one more method call, usually it's a tiny method that can be easily inlined by JIT.
One more thing IMO, is that it is more readable in case of a method reference.
And of course your last point, is well, wrong. You can write for example:
Function<String, Integer> f = String::length
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With