Sub topic 7
Method References: Shorter Lambdas
Many lambdas do only one thing: they call a method that already exists. For example, s -> s.toUpperCase() just passes s to toUpperCase. Java gives you a shorter way to write this, called a method reference.
A method reference is a name for an existing method, written with two colons (::). It can go anywhere a lambda can go. Like a lambda, it needs a functional interface as its target type.
The Basic Idea
These two lines do the same thing:
import java.util.function.Function;
public class Compare {
public static void main(String[] args) {
Function<String, String> upper1 = s -> s.toUpperCase();
Function<String, String> upper2 = String::toUpperCase;
System.out.println(upper1.apply("hi") + " " + upper2.apply("hi")); // HI HI
}
}The method reference String::toUpperCase tells the compiler to call toUpperCase on the input. You don't name the parameter, and you don't write the arrow.
The Four Kinds
There are four kinds of method reference. Each one is shorthand for a different lambda shape.
| Kind | Example | Same as this lambda |
|---|---|---|
| Static method | `Integer::parseInt` | `s -> Integer.parseInt(s)` |
| Method on one specific object (bound) | `prefix::concat` | `s -> prefix.concat(s)` |
| Method on whatever object is passed in (unbound) | `String::toUpperCase` | `s -> s.toUpperCase()` |
| Constructor | `ArrayList::new` | `() -> new ArrayList<>()` |
A bound reference already holds the object it will call. An unbound reference uses the first input as the object.
All Four in Action
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]
}
}Look at line 1. parse.apply("42") returns the number 42, so adding 1 gives 43. If parse returned the string "42", the result would be the text "421".
When the Types Must Match
The compiler checks that the method fits the interface. Integer::parseInt takes a String and returns an int, so it fits Function<String, Integer>. The int is boxed into an Integer for you. It would not fit Supplier<Integer>, because a Supplier takes no input.
Exercises
Exercise
Rewrite the lambda x -> System.out.println(x) as a method reference. Which kind is it?
Show answer
System.out::println. It is a bound instance method reference, because System.out is one specific PrintStream object.
Exercise
What lambda does String::length stand for when its target type is Function<String, Integer>?
Show answer
s -> s.length(). It is an unbound reference, so the input string is the object that length is called on.
Exercise
Can s -> "Hello " + s.trim() be replaced with a single method reference? Why or why not?
Show answer
No. The lambda calls trim and then joins the result to another string. A method reference can stand for only one method call that receives the lambda's inputs directly.