🌐 What are Method References?
A method reference is a shortcut (syntactic sugar) that lets you refer to a method directly — instead of writing a full lambda expression. You can use method references wherever a functional interface is expected.
🔗 Why Use Method References?
✅ They make the code shorter and more readable.
✅ They reuse existing methods instead of rewriting them inside a lambda.
✅ They work beautifully with Streams, functional programming, and lambdas.
💡 Example: Printing a List
✅ Using Lambda
List<String> names = List.of("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));
✅ Using Method Reference (Cleaner)
names.forEach(System.out::println);
System.out::println
is a method reference to println
.
It’s shorthand for name -> System.out.println(name)
.
📚 Types of Method References
Type | Syntax | Example |
---|---|---|
Static method | ClassName::methodName | Math::max |
Instance method on specific object | instance::methodName | System.out::println |
Instance method on arbitrary object of a type | ClassName::methodName | String::toUpperCase |
Constructor reference | ClassName::new | ArrayList::new |
📖 Examples
1️⃣ Static Method Reference
Function<Integer, String> converter = String::valueOf;
// Equivalent to: (num) -> String.valueOf(num)
2️⃣ Instance Method Reference (on specific object)
String prefix = "Hello, ";
Function<String, String> greeter = prefix::concat;
// Equivalent to: name -> prefix.concat(name)
3️⃣ Instance Method Reference (on arbitrary object of a type)
List<String> names = List.of("Alice", "Bob", "Charlie");
names.stream()
.map(String::toUpperCase) // Equivalent to: name -> name.toUpperCase()
.forEach(System.out::println);
4️⃣ Constructor Reference
Supplier<List<String>> supplier = ArrayList::new;
// Equivalent to: () -> new ArrayList<String>()
⚙️ Where are Method References Used?
✅ Streams (map, filter, forEach, etc.)
✅ Callbacks
✅ Functional Interfaces (Consumer
, Supplier
, Function
, Comparator
, etc.)
🧰 Real-World Example: Sorting a List
Lambda
List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie"));
names.sort((a, b) -> a.compareToIgnoreCase(b));
Method Reference
names.sort(String::compareToIgnoreCase);
⚡ When to Use Method References?
Situation | Use |
---|---|
Calling a single existing method directly | ✅ Method Reference |
Need more complex logic (conditions, loops) | ❌ Use Lambda |
📊 Summary Table
Feature | Lambda Expression | Method Reference |
---|---|---|
Flexibility | Any code block | Direct method call only |
Readability | Verbose for simple cases | Very clean |
Performance | Same | Same |
Example | x -> x.toUpperCase() | String::toUpperCase |
🎯 Final Pro Tip
✅ Method references are just shortcuts for lambdas that call existing methods.
✅ They work only when method signature matches functional interface signature.
✅ They make your code more concise and readable, especially with streams.