Lambda Expressions & The 4 Types of Method References
1Concept
Method References (`::`) provide clean shorthand syntax for lambdas that simply call an existing method. There are 4 distinct types: 1. Static (`Class::staticMethod`); 2. Bound Instance (`obj::instanceMethod`); 3. Unbound Instance (`Class::instanceMethod`); 4. Constructor (`Class::new`).
2Architecture Diagram
Lambda: (user) -> user.getName() Method Reference: User::getName (Unbound instance method reference)
3Code Example
Core Java
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
public class MethodReferencesDemo {
static class User {
private String name;
public User() { this.name = "Guest"; }
public User(String name) { this.name = name; }
public String getName() { return name; }
public static boolean isValid(String name) { return name != null && !name.isBlank(); }
}
public static void main(String[] args) {
// 1. Static method reference
Predicate<String> validator = User::isValid;
// 2. Unbound instance method reference
Function<User, String> nameExtractor = User::getName;
// 3. Constructor reference
Supplier<User> userFactory = User::new;
User guest = userFactory.get();
System.out.println("Created via Constructor Reference: " + nameExtractor.apply(guest));
System.out.println("Valid name check: " + validator.test("Alice"));
}
}4Expected Output
Created via Constructor Reference: Guest Valid name check: true
5Key Takeaways
- ✓Method references produce cleaner, more readable code than equivalent verbose lambdas.
- ✓Constructor references (`ArrayList::new`) are ideal for factory suppliers in stream pipelines.
- ✓Variables captured by lambdas MUST be final or effectively final.