What are method references in Java8?

Java8Object Oriented ProgrammingProgramming

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
raja
Published on 08-Apr-2020 16:46:45
Advertisements