A method reference is compact shorthand for a lambda expression that does nothing but call an existing method, using the :: syntax to point directly at that method instead of writing out an explicit lambda parameter list and body.
Key Points: • There are four kinds: static method (ClassName::staticMethod), instance method on a specific object (instance::method), instance method on an arbitrary object of a type (ClassName::instanceMethod), and constructor references (ClassName::new). • A method reference is only valid where the target functional interface's abstract method signature matches the referenced method's parameters and return type. • Method references are purely a syntactic convenience — the compiler converts them into essentially the same bytecode as the equivalent lambda. • They tend to make code more readable when the lambda body would just delegate to an existing method with no additional logic. • If the lambda does any extra work beyond calling one method (such as transforming an argument first), a full lambda is required instead of a method reference.
Example: The lambda x -> System.out.println(x) can be replaced with the method reference System.out::println, and the lambda () -> new ArrayList<>() can be replaced with ArrayList::new.
Code Example:
List<String> names = Arrays.asList("Charlie", "Alice", "Bob");
names.forEach(System.out::println); // instance method ref on a specific object
names.sort(String::compareToIgnoreCase); // instance method ref on arbitrary object
Supplier<List<String>> listFactory = ArrayList::new; // constructor referenceInterview Tip: A concise interview answer is:
"A method reference is just a shorthand for a lambda that does nothing except call an existing method — I use :: to point at the method instead of writing out the parameter and call myself. There are four flavors: static, bound instance, unbound instance, and constructor references, and the compiler treats them the same as the equivalent lambda under the hood."