Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java 8 Method references - can used only in consumer Functional Interfaces

Tags:

java

java-8

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
like image 911
Siva Tharun Avatar asked Sep 03 '26 11:09

Siva Tharun


1 Answers

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
like image 65
Eugene Avatar answered Sep 05 '26 00:09

Eugene