![]() |
VOOZH | about |
Java Method References are a shorthand way to refer to an existing method without invoking it. They were introduced in Java 8 to make lambda expressions shorter, cleaner, and more readable. Method references use the double colon (::) operator and are mainly used with functional interfaces.
Geek1 Geek2 Geek3
Explanation: In the above example, we are using method reference to print items. The print method is a static method which is used to print the names. In the main method we created an array of names and printing each one by calling the print method directly.
ClassName::methodName
objectReference::methodName
ClassName::new
There are four type method references that are as follows:
A static method reference is used to refer to a static method of a class. It replaces a lambda expression that simply calls a static method.
Syntax:
ClassName::staticMethodName
4 9 16
Explanation:
list.forEach(n -> MathUtil.square(n));
This type of method reference refers to an instance method of a specific object. The object is already created, and its method is referenced directly.
Syntax:
objectReference::instanceMethod
Java Spring Boot
Explanation:
printer is an object of the Printer class.printer::print refers to the instance method print().print().data.forEach(msg -> printer.print(msg));
This method reference refers to an instance method of any object of a particular class. The actual object is determined at runtime.
Syntax:
ClassName::instanceMethod
JAVA SPRING MICROSERVICE
Explanation:
map(name -> name.toUpperCase())
A constructor reference is used to create a new object using a functional interface. It replaces a lambda expression that calls a constructor.
Syntax:
ClassName::new
Student object created
Explanation:
Supplier<Student> supplier = () -> new Student();
Method references work only with functional interfaces, which contain exactly one abstract method.
Example:
List<String> list = Arrays.asList("Banana", "Apple", "Mango");
list.sort(String::compareToIgnoreCase);