Java 8 Method Reference – Can only be used for consumer functional interfaces
I’ve been using Java 8 method references for a while, but I have this problem in mind.
I know that a method
reference is a shorthand for a lambda expression that invokes a single method, which can be a static method or a constructor or method that belongs to an instance object.
Does this mean that method references can only be used as a substitute for lambda for consumer functional interfaces?
Consumer<String> c = s -> System.out.println(s);
Can be rewritten as
Consumer<String> c = System.out::println;
Consumer<T> c=(args) -> Class.staticMethod(args)
Can be rephrased as
Of course it can be written like this, which is almost the same behind the scenes. With a method reference, you save another method call internally, usually a tiny method that can be easily inlined via JIT.
Another thing about IMO is that it is more readable in the case of method references.
Of course, your last point is wrong. You can write like this:
Function<String, Integer> f = String::length