Careeroza
Four Kinds of Method References
What is a Method Reference
A method reference (Class::method) is a shortcut for a lambda that only calls one existing method. s -> s.toUpperCase() becomes String::toUpperCase.
| Kind | Syntax | Equivalent 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 of a type | String::length | s -> s.length() |
| Constructor | ArrayList::new | () -> new ArrayList<>() |
All Four in Action
Example
import java.util.*;
import java.util.function.*;
public class Main {
public static void main(String[] args) {
// 1. static method
Function<String, Integer> parse = Integer::parseInt;
System.out.println(parse.apply("42") + 8);
// 2. instance method of a particular object
String greeting = "Namaste";
Predicate<String> startsWithGreeting = greeting::startsWith; // "Namaste".startsWith(x)
System.out.println(startsWithGreeting.test("Nam"));
// 3. instance method of an arbitrary object: first argument becomes the receiver
BiFunction<String, String, Boolean> eqIgnore = String::equalsIgnoreCase;
System.out.println(eqIgnore.apply("JAVA", "java"));
// 4. constructor
Function<String, StringBuilder> sbMaker = StringBuilder::new;
System.out.println(sbMaker.apply("abc").reverse());
List.of("x", "y", "z").forEach(System.out::println);
}
}Output
50 true true cba x y z