Method reference
- Java course
- Intermediate
- Lesson 102/116
- 5 min
Learn method references with Class::method.
Method reference
A method reference is a short way to use an existing method instead of a lambda. The syntax is Class::method. You can write System.out::println instead of s -> System.out.println(s).
There are four kinds: static method (Math::abs), instance method of a type (String::length), instance method of an object (System.out::println) and constructor (User::new). A method reference cannot always replace a lambda; only when the body is a single method call.
When to use a method reference?
When a lambda body is only a single method call, a method reference is more readable. Writing names.forEach(System.out::println); means the same as names.forEach(s -> System.out.println(s)); but shorter.
But if the body has computation, filtering or transformation, a method reference is not enough. For example s -> s.toLowerCase().trim() calls two methods and must stay as a lambda. This is a trade-off between readability and brevity.
Practice forEach with a method reference
Declare List<String> names = new ArrayList<>();; add "Ayşe" and "Alex". Print each element with a method reference using names.forEach(System.out::println);.
Starter code
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Declare List<String>, add two names, print with forEach and method reference
}
}Sample solution
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ayşe");
names.add("Alex");
names.forEach(System.out::println);
}
}Expected output
Ayşe Alex
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the method reference kinds
| Term | Meaning |
|---|---|
Math::abs |
Static method |
String::length |
Type's instance method |
System.out::println |
Instance method |
User::new |
Constructor |
2 Complete the method reference
names.forEach(System.out::____);
names.forEach(System.out::println);
Explanation: The println method reference prints each element.
3 Which lambda is the same as System.out::println?
- s -> s.length()
- s -> System.in.read()
- s -> s.toUpperCase()
- s -> System.out.println(s) Correct answer
Explanation: s -> System.out.println(s) equals System.out::println.