ProLesson 8.3Intermediate2 min readUpdated 30 October 2026
Method references
Make lambdas even shorter with the :: operator, and learn the four kinds of method reference.
When a lambda only calls one existing method, a method reference (::) says the same thing more briefly. s -> s.toUpperCase() becomes String::toUpperCase.
01The four kinds
| Kind | Syntax | Same as lambda |
|---|---|---|
| Static method | Integer::parseInt | s -> Integer.parseInt(s) |
| Instance method of a particular object | System.out::println | x -> System.out.println(x) |
| Instance method of an arbitrary object | String::toUpperCase | s -> s.toUpperCase() |
| Constructor | ArrayList::new | () -> new ArrayList<>() |
MethodRefs.java
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
public class MethodRefs {
static boolean isEven(int n) {
return n % 2 == 0;
}
public static void main(String[] args) {
List<String> raw = List.of("10", "25", "40");
List<Integer> nums = raw.stream().map(Integer::parseInt).toList(); // static
nums.forEach(System.out::println); // particular object
List<String> upper = List.of("java", "spring").stream()
.map(String::toUpperCase).toList(); // arbitrary object
System.out.println(upper);
System.out.println(nums.stream().filter(MethodRefs::isEven).toList()); // your own static method
Supplier<List<String>> listMaker = ArrayList::new; // constructor
List<String> fresh = listMaker.get();
fresh.add("new");
System.out.println(fresh);
Function<String, StringBuilder> toBuilder = StringBuilder::new; // constructor with an argument
System.out.println(toBuilder.apply("abc").reverse());
}
}10 25 40 [JAVA, SPRING] [10, 40] [new] cba
Loading the rest of the lesson…