Method References In Java
Method References
Method references are introduced in Java 8. Method references help to identify methods by their names and it is expressed using :: (double colon) symbol.
A method reference is used to identify the following types of methods.
- Static methods
- Instance methods
- Constructors using new operator
Let’s see an example of Method Reference.
Code
- import java.util.List;
- import java.util.ArrayList;
- public class MethodReferencesExample {
- public static void main(String args[]) {
- List l = new ArrayList();
- l.add("Jack");
- l.add("Bob");
- l.add("Harry");
- l.add("Mia");
- l.forEach(System.out::println);
- }
- }
Output
In the above example, we pass System.out::println method as a static method reference.
Summary
Thus, we learned that Method references help to identify methods by their names and also learns how to use it in Java.