Java Notes
Deep guide to Method References in Java 8 — all four types, when to use vs lambdas, constructor references, and practical patterns.
What is a Method Reference?
A method reference is a shorthand notation for a lambda expression that calls an existing method. It uses the :: operator to refer to a method without invoking it.
// Lambda
names.forEach(name -> System.out.println(name));
// Method Reference (cleaner, more readable)
names.forEach(System.out::println);Method references make code more readable when the lambda does nothing more than call an existing method.
Method Reference vs Lambda: When to Use Which
| Use Method Reference | Use Lambda |
|---|---|
| Simply delegating to existing method | Adding logic beyond method call |
x -> x.toString() → Object::toString | x -> x.toString() + "!" |
x -> System.out.println(x) → System.out::println | x -> { log(x); process(x); } |
| No parameter transformation needed | Parameters need rearranging |
Advanced Patterns
Generic Factory Method
public class ObjectFactory {
private Map<String, Supplier<?>> registry = new HashMap<>();
public <T> void register(String type, Supplier<T> factory) {
registry.put(type, factory);
}
@SuppressWarnings("unchecked")
public <T> T create(String type) {
Supplier<?> factory = registry.get(type);
if (factory == null) throw new IllegalArgumentException("Unknown type: " + type);
return (T) factory.get();
}
public static void main(String[] args) {
ObjectFactory factory = new ObjectFactory();
factory.register("list", ArrayList::new);
factory.register("set", HashSet::new);
factory.register("map", HashMap::new);
List<String> list = factory.create("list");
Set<Integer> set = factory.create("set");
}
}Method Reference in Comparator Chains
List<Employee> employees = getEmployees();
employees.sort(
Comparator.comparing(Employee::getDepartment)
.thenComparing(Employee::getLastName)
.thenComparing(Employee::getFirstName)
.thenComparingDouble(Employee::getSalary)
.reversed()
);
// Extract reusable comparators
Comparator<Employee> byDept = Comparator.comparing(Employee::getDepartment);
Comparator<Employee> bySalaryDesc = Comparator.comparingDouble(Employee::getSalary).reversed();
Comparator<Employee> byName = Comparator.comparing(Employee::getLastName)
.thenComparing(Employee::getFirstName);
employees.sort(byDept.thenComparing(bySalaryDesc));Interview Questions
Q1: What are the four types of method references?
Answer: (1) Static method — ClassName::staticMethod, (2) Instance method of a particular object — instance::method, (3) Instance method of arbitrary object of a type — ClassName::instanceMethod, (4) Constructor — ClassName::new.
Q2: How does the compiler resolve String::length?
Answer: The compiler looks at the target type (e.g., Function<String, Integer>). Since length() is an instance method taking no args, and the functional interface expects a String parameter, the compiler infers the String parameter will be the receiver: s -> s.length().
Q3: Can method references replace all lambdas?
Answer: No. Method references can only replace lambdas that do nothing more than call a single existing method with the same parameters in the same order. If you need extra logic, transformations, or different parameter ordering, you need a lambda.
Q4: What's the difference between System.out::println and PrintStream::println?
Answer: System.out::println is Type 2 (instance of a particular object — specifically System.out). PrintStream::println is Type 3 (instance method of arbitrary PrintStream). The first always prints to stdout; the second requires a PrintStream argument.
Q5: How do constructor references work with generics?
// The compiler infers the generic type from context
Supplier<List<String>> factory = ArrayList::new;
// Compiler infers: () -> new ArrayList<String>()
Function<Integer, List<String>> sizedFactory = ArrayList::new;
// Compiler infers: (size) -> new ArrayList<String>(size)Q6: Can you create a method reference to a private method?
Answer: Yes, but only within the class that owns the private method (same access rules as normal method calls). The lambda/method reference has the same access as the code location where it's written.
Summary
In this chapter, we learned about Method Reference in Java 8 in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Method Reference in Java 8.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, features, method, reference
Related Java Master Course Topics