What are method references?

Method references are a feature of Java 8 . The biggest addition in Java8 has been lambda expressions . Method Reference is the shorthand syntax for a lambda expression that executes just ONE method. It allows us to reference constructors or methods without executing them. Method references and Lambda are similar in that they both require a target type that consist of a compatible functional interface. An interface with only one method is called a functional interface. For example, Comparable, Runnable, AutoCloseable are some functional interfaces in Java. The double colon (::) operator is used for method reference. You can access a method (lambda expression) using the :: notation.

A method reference can be used to point the following types of methods:

  1. Static methods
  2. Instance methods
  3. Constructors using new operator (TreeSet::new)
import java.util.*; public class TestClass { public static void main(String[] args) { List weekDays = new ArrayList(); weekDays.add("Monday"); weekDays.add("Tuesday"); weekDays.add("Wednesday"); weekDays.add("Thursday"); weekDays.add("Friday"); weekDays.forEach(System.out::println); } }