Sub topic 7
Method References: Shorter Lambdas
Many lambdas do only one thing: they call a method that already exists and pass their arguments straight along. Java has a shorter way to write these. It is called a method reference. A method reference is a compact expression that names an existing method so it can be used wherever a matching lambda could go.
In this chapter you will learn what a method reference looks like and the four kinds you can write. You will also learn how to turn a lambda into a method reference, and when it is better to keep the lambda.
What a Method Reference Looks Like
A method reference uses two colons, ::. On the left is a class name, an object, or a variable. On the right is a method name. You never write parentheses or arguments after the method name.
Here is a lambda and the method reference that does the same job:
| Lambda | Method reference |
|---|---|
| `s -> System.out.println(s)` | `System.out::println` |
| `s -> Integer.parseInt(s)` | `Integer::parseInt` |
| `s -> s.toUpperCase()` | `String::toUpperCase` |
| `() -> new ArrayList<>()` | `ArrayList::new` |
Read System.out::println as "the println method of System.out." It does not call println right away. Like a lambda, it creates a value that holds behavior. The method runs later, when someone calls the functional interface's method, such as accept or apply.
Like a lambda, a method reference needs a target type. The target type is the functional interface the compiler expects in that spot. The compiler checks that the named method fits the interface's single abstract method: the right number of parameters, compatible types, and a compatible return type.
A First Example: Lambda vs Method Reference
This program writes the same behavior both ways, so you can compare them.
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class LambdaVsRef {
static boolean isLong(String s) {
return s.length() > 4;
}
public static void main(String[] args) {
Predicate<String> asLambda = s -> LambdaVsRef.isLong(s);
Predicate<String> asRef = LambdaVsRef::isLong;
System.out.println(asLambda.test("banana")); // true
System.out.println(asRef.test("sky")); // false
List<String> words = Arrays.asList("tree", "banana", "sky");
words.forEach(System.out::println); // prints each word on its own line
}
}The lambda s -> LambdaVsRef.isLong(s) takes s and passes it to isLong without changing it. The method reference LambdaVsRef::isLong says the same thing with less text. The s disappears because the compiler already knows the argument goes straight to the method.
The Four Kinds of Method References
Java has four kinds of method references. They differ in what sits on the left of :: and in where the arguments go.
| Kind | Form | Example | Equivalent lambda |
|---|---|---|---|
| Static method | `ClassName::staticMethod` | `Integer::parseInt` | `s -> Integer.parseInt(s)` |
| Bound instance method | `object::method` | `prefix::concat` | `s -> prefix.concat(s)` |
| Unbound instance method | `ClassName::method` | `String::toUpperCase` | `s -> s.toUpperCase()` |
| Constructor | `ClassName::new` | `ArrayList::new` | `() -> new ArrayList<>()` |
This program uses all four:
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
public class MethodRefs {
public static void main(String[] args) {
// 1. Static method
Function<String, Integer> parse = Integer::parseInt;
// 2. Instance method of a particular object (bound)
String prefix = "Item: ";
Function<String, String> addPrefix = prefix::concat;
// 3. Instance method of an arbitrary object of a type (unbound)
Function<String, String> upper = String::toUpperCase;
// 4. Constructor
Supplier<List<String>> newList = ArrayList::new;
System.out.println(parse.apply("42") + 1); // 43
System.out.println(addPrefix.apply("book")); // Item: book
System.out.println(upper.apply("java")); // JAVA
List<String> list = newList.get();
list.add("x");
System.out.println(list); // [x]
}
}Each kind is explained below.
1. Static Method References
A static method is a method that belongs to the class itself, not to any one object. You call it with the class name, like Integer.parseInt("42"). A static method reference passes all of the interface's arguments to the method.
Integer::parseInt fits Function<String, Integer> because parseInt takes a String and returns an int. Java boxes that int into an Integer for you. Boxing means wrapping a primitive value such as int in its matching object type such as Integer.
2. Bound Instance Method References
An instance method is a method you call on one specific object, like prefix.concat("book"). In a bound reference, the object is fixed when you create the reference. The word "bound" means the reference is tied to that one object.
In prefix::concat, the object is the string "Item: ". Every call to addPrefix.apply(x) runs prefix.concat(x) on that same string.
System.out::println is also a bound reference. System.out is one particular object, the standard output stream.
3. Unbound Instance Method References
An unbound reference names a class on the left, but the method is an instance method. No object is chosen yet. The first argument passed in becomes the object the method runs on.
In String::toUpperCase, calling upper.apply("java") runs "java".toUpperCase(). The argument "java" becomes the object.
If the interface has two parameters, the first one becomes the object and the second one becomes the method's argument:
import java.util.function.BiFunction;
import java.util.Comparator;
public class UnboundTwoArgs {
public static void main(String[] args) {
// (a, b) -> a.equalsIgnoreCase(b)
BiFunction<String, String, Boolean> sameText = String::equalsIgnoreCase;
System.out.println(sameText.apply("Java", "JAVA")); // true
// (a, b) -> a.compareToIgnoreCase(b)
Comparator<String> byText = String::compareToIgnoreCase;
System.out.println(byText.compare("apple", "Banana") < 0); // true
}
}Unbound and static references look alike, because both have a class name on the left. To tell them apart, ask whether the method is static. Integer::parseInt is static. String::toUpperCase is not, so it is unbound.
4. Constructor References
A constructor is the special code that runs when you create an object with new. A constructor reference uses the word new as the method name.
ArrayList::new fits Supplier<List<String>> because the ArrayList constructor with no arguments fits get(), which takes nothing and returns a value. If the interface passes arguments, Java picks the constructor that accepts them:
import java.util.function.Function;
public class ConstructorRef {
public static void main(String[] args) {
// s -> new StringBuilder(s)
Function<String, StringBuilder> builder = StringBuilder::new;
StringBuilder sb = builder.apply("abc");
sb.reverse();
System.out.println(sb); // cba
}
}The same StringBuilder::new can mean different constructors in different places. The target type decides which one Java uses.
Choosing the Right Kind
This flowchart shows how to pick the kind of method reference for a lambda.
When to Keep the Lambda
A method reference works only when the lambda passes its arguments straight through, in the same order, with nothing added. Keep the lambda in these cases:
- Extra logic.
s -> s.length() > 4compares the result with 4. There is no single method that does that, so there is no method reference for it. - Changed arguments.
s -> Integer.parseInt(s.trim())callstrimfirst. A method reference cannot do that extra step. - Different argument order.
(a, b) -> b.compareTo(a)uses the second parameter as the object. An unbound reference always uses the first one. - Clarity. Sometimes a lambda is easier to read.
x -> x.getName()andPerson::getNameare both fine, but a long class name on the left can make a reference harder to scan.
Common Mistakes
- Adding parentheses.
String::toUpperCase()does not compile. Write the method name with nothing after it. - Expecting the method to run immediately.
Runnable r = System.out::println;prints nothing untilr.run()is called. (This compiles becauseprintln()with no arguments fitsrun().) - Wrong shape for the target.
Supplier<String> s = String::toUpperCase;fails to compile.get()takes no arguments, so there is no string to calltoUpperCaseon.
Exercise
Rewrite each lambda as a method reference and name its kind: (a) s -> s.length(), (b) n -> Math.abs(n), (c) () -> new HashMap<String, Integer>(), (d) s -> System.out.println(s).
Show answer
(a) String::length, unbound instance method. (b) Math::abs, static method. (c) HashMap::new, constructor (the target type, for example Supplier<Map<String, Integer>>, fills in the type arguments). (d) System.out::println, bound instance method, because System.out is one fixed object.
Exercise
Which of these lambdas cannot be replaced by a method reference, and why? (a) s -> s.isEmpty(), (b) s -> !s.isEmpty(), (c) (a, b) -> a.concat(b), (d) (a, b) -> b.concat(a).
Show answer
(b) and (d) cannot be replaced. Lambda (b) adds the ! operator, which is extra logic. Lambda (d) calls the method on the second parameter, and an unbound reference always calls it on the first. Lambda (a) becomes String::isEmpty and lambda (c) becomes String::concat.
Exercise
Given Function<String, Integer> f = Integer::valueOf; and Function<String, String> g = "Hi "::concat;, what does System.out.println(f.apply("7") + 1); System.out.println(g.apply("Ada")); print?
Show answer
It prints 8 and then Hi Ada. Integer::valueOf is a static reference that turns "7" into the Integer 7, and 7 + 1 is 8. "Hi "::concat is a bound reference on the string "Hi ", so applying it to "Ada" returns "Hi Ada".