All topics
library
intermediate

Method References & Four Types

Use method references as concise alternatives to lambdas, master all four types, and know when lambdas are clearer.

Method references (Java 8) are shorthand for lambdas that simply call an existing method. They're more readable when the lambda body is just a method call.

Method reference = giving someone your business card (the method) instead of writing down your phone number and explaining how to call (the lambda). Both reach you, but the card is more direct.

Key Concepts

1
Four types:
2
1. Static method: Class::staticMethod Lambda equivalent: (args) -> Class.staticMethod(args) Example: Integer::parseInt, Math::abs
3
2. Instance method on a particular object: instance::method Lambda equivalent: (args) -> instance.method(args) Example: System.out::println, myList::add
4
3. Instance method on an arbitrary object: Class::instanceMethod Lambda equivalent: (obj, args) -> obj.instanceMethod(args) Example: String::toLowerCase, String::length The first parameter becomes the receiver.
5
4. Constructor: Class::new Lambda equivalent: (args) -> new Class(args) Example: ArrayList::new, String::new
6
Method references work because the compiler matches the method signature to the functional interface's abstract method. If the signatures match, the reference compiles.
7
When to use: - When the lambda simply delegates to a single method call - When it improves readability (usually does) - Not when you need to transform arguments before the call