Reading — step 1 of 6
Learn
~1 min readModern Java
Method references are a shorter syntax for lambdas that just call an existing method. They make code that uses Streams and functional interfaces dramatically cleaner.
The four kinds
// 1. Static method reference
Function<String, Integer> parse = Integer::parseInt;
// equivalent to: s -> Integer.parseInt(s)
// 2. Instance method on a specific object
List<String> log = new ArrayList<>();
Consumer<String> append = log::add;
// equivalent to: s -> log.add(s)
// 3. Instance method on the class (the receiver becomes the first arg)
Function<String, String> upper = String::toUpperCase;
// equivalent to: s -> s.toUpperCase()
// 4. Constructor reference
Supplier<ArrayList<String>> newList = ArrayList::new;
// equivalent to: () -> new ArrayList<>()
Function<Integer, ArrayList<String>> sized = ArrayList::new;
// equivalent to: n -> new ArrayList<>(n) — picks the matching constructor
When method references shine
Classic stream pipelines:
// With lambdas:
list.stream()
.filter(s -> s != null)
.map(s -> s.trim())
.map(s -> s.toUpperCase())
.forEach(s -> System.out.println(s));
// With method references:
list.stream()
.filter(Objects::nonNull)
.map(String::trim)
.map(String::toUpperCase)
.forEach(System.out::println);
The second reads as a pipeline of named operations rather than a sequence of one-arg lambdas. It's also faster for the JIT to inline.
When NOT to use them
A lambda is clearer when:
- You need to pass extra arguments:
n -> Math.max(n, 0)doesn't compress - You're transforming the value:
s -> s + "!"— no method reference for that - The reader has to look up what the method does — explicit is better
Common mistakes
- Confusing
String::toUpperCasewith"hi"::toUpperCase— first is unbound (takes a String arg); second is bound to a specific String. - Type inference failing — sometimes the compiler can't pick the right overload; cast to disambiguate.
ArrayList::newwith multiple constructors — picks based on the target functional-interface signature.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…