Method references helps to use methods by their names. A method reference is described using "::" symbol.
A method reference can be used for following types of methods : -
- Static methods
- Instance methods
- Constructors using new operator (TreeSet::new)
Method Reference Example: -
Java8MethodReference.java
import java.util.List;
import java.util.ArrayList;
import java.util.ArrayList;
public class Java8Tester {
public static void main(String args[]) {
List names = new ArrayList();
names.add("Mahesh");
names.add("Suresh");
names.add("Ramesh");
names.add("Naresh");
names.add("Kalpesh");
names.forEach(System.out::println);
}
}
We know, println() method is a instance method of "System.out" object. But now we can call println() method with their name only as an instance method reference.
Ex- System.out::println
Output:-
Mahesh
Suresh
Ramesh
Naresh
Kalpesh