Method References are shorthand for lambda expressions that call a single method. They make code more readable and concise.
| Type | Syntax | Example |
|---|---|---|
| Static Method | Class::staticMethod | Math::max |
| Instance Method | object::method | str::length |
| Arbitrary Object | Class::instanceMethod | String::toUpperCase |
| Constructor | Class::new | ArrayList::new |
// Lambda vs Method Reference
list.forEach(s -> System.out.println(s)); // Lambda
list.forEach(System.out::println); // Method Reference
// More examples
list.stream().map(String::toUpperCase); // Instance method
list.stream().sorted(Integer::compare); // Static method
list.stream().collect(ArrayList::new); // ConstructorJava 8+ | Lambda | Stream API
Keywords: Java Method-Reference Lambda Functional-Programming Stream-API Java8