Java Method References and Constructor References
Master Java method references (::): object::instanceMethod, Class::instanceMethod, Class::staticMethod, this:: and super::, how overloads are chosen, the null difference from lambdas, and constructor references such as Person::new and Person[]::new for streams and generic arrays.
kvi5hnuCode Sprout team member10 min readOn this page
Sometimes a lambda expression does nothing but call one existing method. Suppose you simply want to print the event object whenever a timer fires. You could write
var timer = new Timer(1000, event -> System.out.println(event));
It would be nicer to pass the println method itself to the Timer constructor. Here's how:
var timer = new Timer(1000, System.out::println);
The expression System.out::println is a method reference. It tells the compiler to produce an instance of a functional interface whose single abstract method calls the given method. Here an ActionListener is produced whose actionPerformed(ActionEvent e) method calls System.out.println(e).
Which println?
PrintStream (the class of System.out) has ten overloaded println methods. The compiler picks one based on the context. In the timer example, System.out::println must become an ActionListener with the method void actionPerformed(ActionEvent e). Of the ten overloads, println(Object x) is the best match for an ActionEvent, so it's selected, and the event object is printed on each tick.
Assign the same method reference to a different functional interface, and a different overload is chosen:
Runnable task = System.out::println;
Runnable's single method void run() has no parameters, so the parameterless println() is chosen, and task.run() prints a blank line.
Similarly, Math.max has versions for int, long, float and double. Which one Math::max refers to depends on the parameter types of the functional interface it's converted to. Just like lambdas, method references never live in isolation: they're always turned into instances of functional interfaces.
The Three Kinds of Method References
The :: operator separates the method name from the name of an object or a class. There are three variants:
object::instanceMethodClass::instanceMethodClass::staticMethod

object::instanceMethod: the lambda's parameters are passed to the method. WithSystem.out::println, the object isSystem.out, and the reference is equivalent tox -> System.out.println(x).Class::instanceMethod: the first parameter becomes the implicit parameter (the receiver) of the method.String::compareToIgnoreCaseis the same as(x, y) -> x.compareToIgnoreCase(y). To sort strings regardless of case, writeArrays.sort(strings, String::compareToIgnoreCase).Class::staticMethod: all parameters are passed to the static method.Math::powis equivalent to(x, y) -> Math.pow(x, y).
More examples:
| Method reference | Equivalent lambda | Notes |
|---|---|---|
separator::equals | x -> separator.equals(x) | An object and an instance method; the lambda parameter is passed as the explicit argument |
String::strip | x -> x.strip() | A class and an instance method; the lambda parameter becomes the implicit parameter |
String::concat | (x, y) -> x.concat(y) | An instance method with an explicit parameter: the first lambda parameter is the receiver, the rest are arguments |
Integer::valueOf | x -> Integer.valueOf(x) | A static method; the parameter is passed along |
Integer::sum | (x, y) -> Integer.sum(x, y) | A static method with two parameters. Integer.sum was created specifically for use as a method reference; as a lambda, you'd just write (x, y) -> x + y |
String::new | x -> new String(x) | A constructor reference (see below) |
String[]::new | n -> new String[n] | An array constructor reference; the parameter is the length |
A lambda can be rewritten as a method reference only if its body calls a single method and does nothing else. s -> s.length() == 0 has a single method call, but also a comparison, so there's no method reference for it. (String::isEmpty happens to do the same thing, which is often how you find a reference: look for a method that already does what your lambda does.)
Methods made for method references
Some API methods exist mainly to be used as method references. Objects.isNull tests whether a reference is null. At first glance it seems pointless, since obj == null is easier to read than Objects.isNull(obj). But you can pass Objects::isNull to any method with a Predicate parameter:
list.removeIf(Objects::isNull); // a bit easier to read than list.removeIf(e -> e == null)
Other examples are Objects::nonNull, Integer::sum, Integer::max, String::isBlank, Predicate.not(String::isBlank) and Function.identity().
A subtle difference: when the receiver is evaluated
There's a tiny difference between an object::method reference and its equivalent lambda. In a method reference such as separator::equals, the expression before :: is evaluated immediately, when the reference is created. If separator is null, forming separator::equals throws a NullPointerException right away. The lambda x -> separator.equals(x) throws only when it's invoked. The same applies to side effects: in makeObject()::method, makeObject() runs once, at creation time, not on each call.
this:: and super::
You can capture this in a method reference: this::equals is the same as x -> this.equals(x). It's also valid to use super. The expression
super::instanceMethod
uses this as the target and invokes the superclass version of the method. Here's an artificial example showing the mechanics:
class Greeter {
public void greet(ActionEvent event) {
System.out.println("Hello, the time is " + Instant.ofEpochMilli(event.getWhen()));
}
}
class RepeatedGreeter extends Greeter {
public void greet(ActionEvent event) {
var timer = new Timer(1000, super::greet);
timer.start();
}
}
When RepeatedGreeter.greet starts, it constructs a Timer that runs super::greet, the Greeter version, on every tick. The demo below does the same without a GUI.
Constructor References
Constructor references are just like method references, except that the method name is new. Person::new is a reference to a Person constructor. Which constructor? It depends on the context.
Suppose you have a list of strings and want a list of Person objects, calling the constructor on each string:
ArrayList<String> names = . . .;
Stream<Person> stream = names.stream().map(Person::new);
List<Person> people = stream.toList();
Streams (stream, map, toList) are covered in depth in the streams material. For now, what matters is that map calls the Person(String) constructor for each element. If Person has several constructors, the compiler picks the one with a String parameter, because it infers from the context that the constructor is called with a string. (Stream.toList() arrived in Java 16; before that you'd write collect(Collectors.toList()).)
Constructor references with no arguments match Supplier: Supplier<List<String>> factory = ArrayList::new;. That's handy for APIs such as Collectors.toCollection(TreeSet::new). Watch out for Map.computeIfAbsent(key, ...): it takes a Function and passes the key to it, so ArrayList::new there would mean new ArrayList<>(key), a compile error for a String key and, worse, an initial capacity for an Integer key. Write the lambda k -> new ArrayList<>() instead.
Array constructor references
You can form constructor references with array types. int[]::new has one parameter, the length, and is equivalent to n -> new int[n].
Array constructor references overcome a limitation of Java: you can't construct an array of a generic type T. The expression new T[n] is an error, because it would be "erased" to new Object[n] (see the generics part). That's a problem for library authors. Suppose we want an array of Person objects from a stream. Stream.toArray() returns an Object[]:
Object[] people = stream.toArray();
That's unsatisfactory: the user wants Person[], not Object[]. The stream library solves the problem with constructor references. Pass Person[]::new to toArray:
Person[] people = stream.toArray(Person[]::new);
toArray calls this constructor to obtain an array of the correct type, then fills and returns it. Collections offer the same since Java 11: list.toArray(String[]::new).
Everything in One Program
import java.util.*;
import java.util.function.*;
import java.util.stream.Stream;
public class Solution {
public static void main(String[] args) {
// 1. object::instanceMethod == x -> System.out.println(x)
Consumer<String> printer = System.out::println;
printer.accept("printed by a method reference");
// the same reference, a different functional interface: println() is chosen
Runnable blankLine = System.out::println;
blankLine.run();
// 2. Class::instanceMethod == (x, y) -> x.compareToIgnoreCase(y)
String[] strings = { "banana", "Apple", "cherry", "apple" };
Arrays.sort(strings, String::compareToIgnoreCase);
System.out.println(Arrays.toString(strings));
Function<String, String> strip = String::strip; // x -> x.strip()
BinaryOperator<String> concat = String::concat; // (x, y) -> x.concat(y)
System.out.println("[" + strip.apply(" hi ") + "] " + concat.apply("foo", "bar"));
// 3. Class::staticMethod == (x, y) -> Math.pow(x, y)
DoubleBinaryOperator pow = Math::pow;
BinaryOperator<Integer> sum = Integer::sum;
IntBinaryOperator maxInt = Math::max; // max(int, int) is picked
DoubleBinaryOperator maxDouble = Math::max; // max(double, double) is picked
System.out.println(pow.applyAsDouble(2, 10) + " " + sum.apply(3, 4) + " "
+ maxInt.applyAsInt(3, 7) + " " + maxDouble.applyAsDouble(2.5, 1.5));
// methods designed to be used as method references
var list = new ArrayList<>(Arrays.asList("a", null, "b"));
list.removeIf(Objects::isNull);
System.out.println(list);
// a bound reference evaluates its receiver immediately
String separator = null;
Predicate<String> lambda = x -> separator.equals(x); // fine until invoked
try {
Predicate<String> ref = separator::equals; // throws right here
} catch (NullPointerException e) {
System.out.println("separator::equals threw NullPointerException at creation");
}
// this:: and super::
new RepeatedGreeter().greet("tick");
// constructor references
List<String> names = List.of("Ada", "Linus", "Grace");
List<Person> people = names.stream().map(Person::new).toList(); // Person(String)
System.out.println(people);
IntFunction<int[]> makeArray = int[]::new; // n -> new int[n]
System.out.println(makeArray.apply(4).length);
Person[] array = names.stream().map(Person::new).toArray(Person[]::new);
System.out.println(array.getClass().getSimpleName() + " " + array.length);
Supplier<List<String>> listFactory = ArrayList::new;
List<String> fresh = listFactory.get();
fresh.add("new list");
System.out.println(fresh);
// surprise: setAll passes the index, so new Date(long) is called
var dates = new Date[3];
Arrays.setAll(dates, Date::new);
for (Date d : dates) System.out.print(d.getTime() + " ");
System.out.println("(milliseconds since the epoch, not now)");
}
}
record Person(String name) { }
class Greeter {
public void greet(String event) {
System.out.println("Hello, the event is " + event);
}
}
class RepeatedGreeter extends Greeter {
@Override
public void greet(String event) {
Consumer<String> parent = super::greet; // calls Greeter.greet on this object
Consumer<String> self = this::shout; // same as x -> this.shout(x)
for (int i = 1; i <= 2; i++) parent.accept(event + " " + i);
self.accept(event);
}
private void shout(String event) {
System.out.println(event.toUpperCase() + "!");
}
}
printed by a method reference
[Apple, apple, banana, cherry]
[hi] foobar
1024.0 7 7 2.5
[a, b]
separator::equals threw NullPointerException at creation
Hello, the event is tick 1
Hello, the event is tick 2
TICK!
[Person[name=Ada], Person[name=Linus], Person[name=Grace]]
4
Person[] 3
[new list]
0 1 2 (milliseconds since the epoch, not now)
(The blank second line is Runnable blankLine = System.out::println at work.)
Lambdas or Method References?
Both compile to the same kind of object, so choose for readability:
- Prefer a method reference when it's shorter and clearer:
map(String::trim),forEach(System.out::println),sorted(Comparator.comparing(Person::name)). - Prefer a lambda when the reference would be obscure or would need a helper method just to exist, or when parameters need meaningful names:
(order, customer) -> order.isFor(customer)may read better thanOrder::isFor. - IDEs such as IntelliJ IDEA offer to convert between the two forms in either direction.
Common questions
Is a method reference faster than the equivalent lambda?
No meaningful difference. Both are linked through invokedynamic and optimised by the JIT. Choose whichever reads better.
Why does list.forEach(System.out::println) work but list.forEach(println) doesn't?
Java has no free functions. Every method reference must name the class or object it belongs to: System.out::println, String::length, this::process. Inside the class itself, this::method or ClassName::staticMethod is needed.
What does String::length become in Function<String, Integer>?
s -> s.length(). The first lambda parameter becomes the object the method is called on. The same reference also fits ToIntFunction<String> with no boxing.
Can I use a method reference to a constructor with several arguments?
Yes. Person::new adapts to any functional interface whose parameters match one of the constructors, for example BiFunction<String, Integer, Person> for Person(String, int). Beyond two arguments there's no standard functional interface, so define your own.
Why does map(Integer::toString) sometimes fail to compile?
Integer has both a static toString(int) and an instance toString(). With a Function<Integer, String> target, both readings fit, and the reference is ambiguous. Write a lambda i -> i.toString(), or use String::valueOf or Object::toString.
Summary
- A method reference
X::mproduces a functional interface instance that callsm. Like a lambda, it needs a target type. object::instanceMethodpasses all parameters as arguments.Class::instanceMethoduses the first parameter as the receiver.Class::staticMethodpasses all parameters to the static method.- Overloads are resolved from the functional interface's parameter types (
System.out::printlnasRunnablecallsprintln()). this::mandsuper::mcapture the current object;super::mcalls the superclass version.- In
expr::m,expris evaluated when the reference is created, so anullreceiver throws immediately. - Constructor references
Class::newand array constructor referencesType[]::newlet APIs create objects and arrays of the right type, as instream.toArray(Person[]::new).
Practice Questions
Rewrite these lambdas as method references: s -> s.toUpperCase(), (a, b) -> a.compareTo(b), x -> Math.abs(x), () -> new HashMap<>()
String::toUpperCase, String::compareTo (or Comparator.naturalOrder()), Math::abs, and HashMap::new.
Why can't s -> s.length() > 3 be written as a method reference?
Its body does more than call one method: it also compares the result with 3. A method reference can only stand for a single method call with the lambda parameters passed through.
What does Runnable r = System.out::println; r.run(); print, and why?
A blank line. Runnable.run has no parameters, so the compiler picks the parameterless println() overload.
String prefix = null; Predicate<String> p = prefix::equals; Where exactly does the NullPointerException happen?
At the assignment, when the method reference is created, because the receiver expression prefix is evaluated immediately. The lambda s -> prefix.equals(s) would fail only when p.test(...) is called.
Convert a List<String> names into a String[] with a constructor reference.
String[] array = names.toArray(String[]::new); or names.stream().toArray(String[]::new).
Arrays.setAll(dates, Date::new) doesn't fill the array with today's date. What does it do, and how do you fix it?
setAll passes each index to an IntFunction, so new Date(long) is called with 0, 1, 2, … milliseconds after the epoch. Use Arrays.setAll(dates, i -> new Date()), or better, the immutable java.time classes.
Previous: Java Lambda Expressions and Functional Interfaces
Next: Java Lambda Variable Scope, Processing Lambdas and Comparator Methods
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.