Modern Java 8+ Features ยท Lambdas and Functional Interfaces

Method References

When a lambda only calls an existing method, write Class::method instead. Four kinds: static, of the argument, of an object, and constructors.

MethodRefDemo.java

import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;

public class MethodRefDemo {
    static int doubleIt(int n) {
        return n * 2;
    }

    public static void main(String[] args) {
        Function<Integer, Integer> viaLambda = n -> doubleIt(n);
        Function<Integer, Integer> viaRef = MethodRefDemo::doubleIt;   // static method
        Function<String, Integer> length = String::length;            // method of the argument
        Supplier<StringBuilder> maker = StringBuilder::new;            // constructor

        int a = viaLambda.apply(4);
        int b = viaRef.apply(4);
        int len = length.apply("java");
        StringBuilder sb = maker.get();
        List.of("x", "y").forEach(System.out::println);                 // method of an object
        System.out.println(a + " " + b + " " + len + " " + sb.length());
    }
}

Step by step

  1. A lambda that just calls doubleIt.
  2. The same thing as a method reference: "use MethodRefDemo's doubleIt".
  3. String::length means "call length() on whatever string is passed in".
  4. StringBuilder::new refers to a constructor.
  5. Java calls lambda$main$0(), with n = 4. It gets its own variables on the stack.
  6. A lambda that just calls doubleIt.
  7. doubleIt() has finished, so its variables are gone.
  8. A lambda that just calls doubleIt.
  9. The value it returned, 8, is stored in a.
  10. Java calls doubleIt(), with n = 4. It gets its own variables on the stack.
  11. doubleIt() has finished, so its variables are gone.
  12. The value it returned, 8, is stored in b.
  13. len is created on the stack with the value 4.
  14. sb is created on the stack and points to a new StringBuilder on the heap: .
  15. System.out::println: the println method of the System.out object, called for each item.
  16. It prints 8 8 4 0.
  17. The lambda and the reference both doubled 4 to 8. Method references are shorthand when a lambda only forwards to a method.