Modern Java 8+ Features ยท Lambdas and Functional Interfaces
When a lambda only calls an existing method, write Class::method instead. Four kinds: static, of the argument, of an object, and constructors.
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());
}
}lambda$main$0(), with n = 4. It gets its own variables on the stack.doubleIt() has finished, so its variables are gone.a.doubleIt(), with n = 4. It gets its own variables on the stack.doubleIt() has finished, so its variables are gone.b.len is created on the stack with the value 4.sb is created on the stack and points to a new StringBuilder on the heap: .8 8 4 0.