How to Use Method Reference in Java 8 with Example

A method reference in Java 8 is used as a shorthand for a lambda expression when we want to call an existing method. It works with a functional interface and makes the code shorter and more readable. To call a static method using a method reference, we use the syntax ClassName::staticMethodName.

 

Lambda vs Method Reference

The method reference version is shorter and cleaner than the lambda expression when the lambda only calls an existing method.
Lambda:
Test e = name -> MethodReferenceTest.getInfo(name);
Method Reference:
Test e = MethodReferenceTest::getInfo;

Code Explanation (Step-by-Step)

  • Test is a functional interface because it contains only one abstract method.
  • The lambda expression prints the given name.
  • MethodReferenceTest::getInfo is a method reference to the static method getInfo.
  • When e1.getName(“Ankit”) is called, Java internally calls getInfo(“Ajay”).
				
					interface Test {
	public void getName(String name);
}

public class MethodReferenceTest {
	public static void getInfo(String info) {
		System.out.println("checking:- " + info);
	}
	public static void main(String[] args) {
		Test e = (String name) -> {
			System.out.println("welcome:- " + name);
		};
		e.getName("Ankit");
		Test e1 = MethodReferenceTest::getInfo;
		e1.getName("Ajay");
	}
}
				
			

Output :-
welcome:- Ankit
checking:- Ajay