What are method references in Java8?
https://www.tutorialspoint.com/what-are-method-references-in-java8
-
13-09-2020 - |
Pregunta
What are method references in Java8?
Lambda expressions In Java allows you to pass functionality as an argument to a method. You can also call an existing method using lambda expressions.
list.forEach(n -> System.out.println(n));
Method references are simple, easy-to-read lambda expressions to call/refer and the existing method by name in a lambda expression.
Syntax
Object:methodName
Example
Suppose, if we have an interface named myInterface, we can pass the functionality/implementation as object value as shown below −
interface myInterface{ void greet(); } public class MethodReferences { public static void main(String args[]) { myInterface in = ()->System.out.println("Sample method");; in.greet(); } }
If we already have an implementation of this method, we can use lambda expression as −
interface myInterface{ void greet(); } public class MethodReferences { public void demo() { System.out.println("Sample method"); } public static void main(String args[]) { MethodReferences obj = new MethodReferences(); myInterface in = ()-> obj.demo(); in.greet(); } }
You can refer the existing method using the method references instead of a lambda expression as −
interface myInterface{ void greet(); } public class MethodReferences { public void demo() { System.out.println("Sample method"); } public static void main(String args[]) { MethodReferences obj = new MethodReferences(); myInterface in = obj::demo; in.greet(); } }
Output
Sample method
Advertisements
No afiliado a Tutorialspoint