All topics
library
intermediate

Method References

Use the four types of method references as shorthand for lambdas that call a single existing method.

Method references are a concise alternative to lambdas when the lambda body simply calls an existing method. There are four types:

Lambda = 'hey, take this and pass it to the printer.' Method reference = 'just use the printer directly.'

Key Concepts

1
1. Static method: ClassName::staticMethod — e.g., Integer::parseInt for s -> Integer.parseInt(s) 2. Instance method of a particular object: instance::method — e.g., System.out::println for x -> System.out.println(x) 3. Instance method of an arbitrary object: ClassName::instanceMethod — e.g., String::toUpperCase for s -> s.toUpperCase(). The first parameter becomes the receiver. 4. Constructor: ClassName::new — e.g., ArrayList::new for () -> new ArrayList<>()
2
Method references improve readability when the lambda just delegates. They don't work when you need to transform arguments, call multiple methods, or add logic.
3
Type 3 is the trickiest: String::compareTo is a method reference for (a, b) -> a.compareTo(b). The first parameter becomes 'this' and the second becomes the argument.
4
Method references can also work with generics: Map::entry for Map.Entry::new.