Stop 09 · Lambdas & StreamsTopics · 3/7

Method References

Part of the Java Roadmap

In short

Half the lambdas you write just call one existing method. Method references let you name that method directly, which makes stream code read like a list of steps.

Method references like String::toUpperCase or System.out::println are shorter forms of lambdas that just call an existing method.

The jaadu presses a single big button on an old desk phone covered in rows of speed dial buttons, looking pleased.

Think of it like this

Speed dial

Instead of typing 'call 98765 43210 and ask for Amma' every time, you save Amma on speed dial and press one button. A method reference like String::toUpperCase is that button: it points at work that already exists instead of describing it again.

Watch it happen

The four kinds of method reference

Integer::parseInt
0
String::toUpperCase
1
System.out::println
2
ArrayList::new
3

1/5Each one is a shortcut for a lambda that only calls one method.

The big ideas

What you need to know

Same thing, shorter

A method reference compiles to the same functional interface as the matching lambda. It is purely about readability.

Four forms

Class::staticMethod, Class::instanceMethod, object::instanceMethod and Class::new for constructors.

Shapes must match

The method's parameters and return type must fit the interface. Integer::parseInt fits Function<String, Integer>.

Use when it helps

Prefer Order::amount over o -> o.amount(). Keep the lambda if you need extra arguments or logic.

See it in code

Walk through the code

java
1import java.util.ArrayList;2import java.util.List;3import java.util.function.Supplier;4 5public class MethodRefDemo {6    public static void main(String[] args) {7        List<String> prices = List.of("120", "450", "99");8 9        List<Integer> numbers = prices.stream()10                .map(Integer::parseInt)          // static method11                .toList();12 13        List<String> cities = List.of("pune", "delhi", "kochi");14        cities.stream()15              .map(String::toUpperCase)          // method on each element16              .forEach(System.out::println);     // method on one object17 18        Supplier<List<String>> newList = ArrayList::new; // constructor19        List<String> basket = newList.get();20        basket.add("Mangoes");21 22        System.out.println(numbers + " " + basket); // [120, 450, 99] [Mangoes]23    }24}

1/4Integer::parseInt turns each price string into an Integer.

All four kinds of method reference in one small program. Stream.toList() needs Java 16 or newer.

Save yourself the pain

Common mistakes

Oops

map(String::toUpperCase()) with brackets.

Do this instead

No brackets. A method reference names the method, it does not call it: map(String::toUpperCase).

Oops

Forcing a method reference when you need extra values: map(String::substring).

Do this instead

Use a lambda when you pass extra arguments: map(s -> s.substring(0, 3)).

Your mission

Lambda to reference

~15 min

Quick check

Which lambda is the same as String::length used in map()?

Go deeper

  1. 1Replace x -> System.out.println(x) with System.out::println.
  2. 2Practise the four kinds: static, instance, arbitrary object and constructor references.
  3. 3Use whichever form, lambda or reference, reads more clearly.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge