🔎 What is a Method Reference?
A method reference is a compact, readable way to refer to an existing method by name rather than writing a full lambda.
It’s basically a lambda that just calls an existing method.
✅ Basic Syntax
ClassName::methodName
// or
objectInstance::methodName
🔹 Types of Method References
Type | Syntax | Example |
---|---|---|
Reference to a static method | ClassName::staticMethod | Math::max |
Reference to an instance method of a specific object | instance::instanceMethod | System.out::println |
Reference to an instance method of an object of a particular type | ClassName::instanceMethod | String::toLowerCase |
Reference to a constructor | ClassName::new | ArrayList::new |
🧪 Examples
✅ 1. Static Method Reference
List<Integer> nums = Arrays.asList(3, 1, 2);
nums.sort(Integer::compare); // equivalent to (a, b) -> Integer.compare(a, b)
✅ 2. Instance Method Reference of a Specific Object
PrintStream printer = System.out;
List<String> names = Arrays.asList("Alice", "Bob");
names.forEach(printer::println); // instead of: name -> printer.println(name)
✅ 3. Instance Method Reference of Any Object of a Particular Type
List<String> words = Arrays.asList("Java", "is", "cool");
words.sort(String::compareToIgnoreCase); // instead of (a, b) -> a.compareToIgnoreCase(b)
✅ 4. Constructor Reference
Supplier<List<String>> supplier = ArrayList::new;
List<String> list = supplier.get(); // Creates a new ArrayList
🧠 When to Use Method References?
- When the lambda just calls an existing method
- For cleaner, more expressive code
- To improve readability in streams, filters, sorting, etc.
🔄 Lambda vs Method Reference Example
// Lambda
list.forEach(s -> System.out.println(s));
// Method reference
list.forEach(System.out::println);
Same result, but the second is more concise and readable.