Method references
A lambda whose body is one call of an existing method can be written as a method reference: s -> s.length() becomes String::length. The form says what is called and leaves the arguments to the compiler, and it is shorter in the place where a lambda is already short: inside a stream pipeline.
The four kinds
The double colon has four shapes, and the program shows one of each: a static method, a method of an existing object, a method of the object that will be the argument, and a constructor:
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
public class Kinds {
public static void main(String[] args) {
Function<String, Integer> parse = Integer::parseInt;
System.out.println(parse.apply("42"));
List<String> words = new ArrayList<>(List.of("a", "b"));
words.forEach(System.out::println);
Function<String, Integer> length = String::length;
System.out.println(length.apply("hello"));
Supplier<List<String>> empty = ArrayList::new;
System.out.println(empty.get().size());
BiFunction<String, Integer, Person> factory = Person::new;
System.out.println(factory.apply("Ada", 36));
}
}
record Person(String name, int age) {
}
javac -Xlint:all Kinds.java
java Kinds
42
a
b
5
0
Person[name=Ada, age=36]
Integer::parseInt is a static method that takes a string and returns an int, which is the shape of Function<String, Integer> after boxing. System.out::println is bound to one object, the standard output stream, and the list passes each element to it. Both are accept calls with no visible argument, which is the point of the shorter form.
Bound and unbound
System.out::println is bound: the receiver is named before the colons and the lambda takes only the argument. String::length is unbound: the receiver is not named yet, so the lambda takes it as the first parameter, which is why a Function<String, Integer> fits. The two forms are written the same way and differ only in whether a name precedes the colons.
The rule for the compiler is mechanical: a static reference uses the arguments of the interface; a bound reference uses them after the receiver; an unbound reference uses the first argument as the receiver and the rest as arguments. That is why String::compareTo can be a BiFunction<String, String, Integer> and list::add is a Consumer<String>.
Constructor references
ClassName::new is a constructor as a function, and the interface decides which constructor: a Supplier takes the no-argument one, Person::new in a BiFunction takes the two-argument one, and an array reference String[]::new takes an int and answers an array. A class with several constructors gets one reference per shape, chosen by the target type.
A chain of references
A stream pipeline is where the form earns its keep: three references in a row, each shorter than the lambda it replaces:
import java.util.List;
import java.util.stream.Collectors;
public class Chain {
public static void main(String[] args) {
List<String> words = List.of(" pear ", " fig ", " apple");
List<String> clean = words.stream()
.map(String::strip)
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(clean);
System.out.println(words.stream().map(String::length).collect(Collectors.toList()));
words.stream().map(String::strip).forEach(System.out::println);
}
}
javac -Xlint:all Chain.java
java Chain
[PEAR, FIG, APPLE]
[7, 6, 6]
pear
fig
apple
The first line strips the spaces and upper-cases, and the second counts the characters of the strings before the strip, where the spaces still count: pear is seven with two spaces, fig is six, apple is six. The third line prints the stripped words one per line through the bound reference. The stream itself is the next lesson; the references would work in any method that takes a function.
The reference that does not fit
A method reference is checked against the target type like any lambda, and a return type that does not match is an error at the reference:
import java.util.function.Function;
public class Wrong {
public static void main(String[] args) {
Function<String, Integer> f = String::toUpperCase;
System.out.println(f.apply("x"));
}
}
javac -Xlint:all Wrong.java
Wrong.java:5: error: incompatible types: bad return type in method reference
Function<String, Integer> f = String::toUpperCase;
^
String cannot be converted to Integer
1 error
The message names the mismatch and the two types, and the caret points at the reference. String::toUpperCase is a fine reference for a Function<String, String> or a UnaryOperator<String>; the fault is the declared result, not the method.
Exercises
- Write parse.apply of Kinds as a lambda and compare the two lines.
- Make a Comparator from String::compareTo and sort a list with it.
- Build an array of strings with String[]::new from an IntFunction.
- Change the Chain to print the length after the strip and explain the new numbers.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
String::lengthmean?Answer
An unbound reference that takes the string as its argument
No receiver is named, so the interface passes the string as the first argument.
-
What does
System.out::printlnmean?Answer
A reference bound to the standard output stream
The receiver is named before the colons, so the lambda takes only the value to print.
-
Which reference builds an object?
Answer
ClassName::new
new is the constructor, and the target type chooses which one.
-
What does this program print?
import java.util.function.Function; public class Q1 { public static void main(String[] args) { Function<String, Integer> f = Integer::parseInt; System.out.println(f.apply("7") + 1); } }Answer
8
The reference parses the string to 7 and the value is added to one.
-
What does this program print?
import java.util.ArrayList; import java.util.List; public class Q2 { public static void main(String[] args) { List<String> list = new ArrayList<>(List.of("a", "b")); list.forEach(System.out::print); System.out.println(); } }Answer
ab
The bound reference prints each element with no separator, so the two are joined.
-
What does this program print?
import java.util.function.Function; public class Q3 { public static void main(String[] args) { Function<String, String> f = String::toUpperCase; System.out.println(f.apply("abc")); } }Answer
ABC
The unbound reference calls the method on its argument, which upper-cases the text.
-
What does this program print?
import java.util.function.BiFunction; public class Q4 { public static void main(String[] args) { BiFunction<String, Integer, P> make = P::new; System.out.println(make.apply("a", 1)); } } record P(String name, int n) { }Answer
P[name=a, n=1]
The constructor reference takes the two arguments and the record prints its components.
-
What does this program print?
import java.util.function.Supplier; public class Q5 { public static void main(String[] args) { Supplier<String> s = "hello"::toUpperCase; System.out.println(s.get()); } }Answer
HELLO
The reference is bound to one string, so the supplier calls the method on it with no argument.
-
What is the first line of the compiler output for this program?
import java.util.function.Function; public class Q6 { public static void main(String[] args) { Function<String, Integer> f = String::toUpperCase; System.out.println(f.apply("x")); } }Answer
error: incompatible types: bad return type in method reference
The method returns a String where the interface promises an Integer.
-
When is a method reference clearer than a lambda?
Answer
When the lambda only calls one existing method with the arguments as they come
The reference names the method and drops the parameter list that adds nothing.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev