Reference to a static method using method references in Java8

Java 8Object 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. You can refer to a static method defined in the class using method references.

Syntax

Following is the syntax to reference a static method in Java

ClassName:methodName

Example

The following Java example references a static method in Java.

interface myInterface{
   void greet();
}
public class MethodReferences {
   public static void demo() {
      System.out.println("Sample method");
   }
   public static void main(String args[]) {
      myInterface in = MethodReferences::demo;
      in.greet();
   }
}

Output

Sample method
raja
Published on 08-Apr-2020 16:49:42
Advertisements