The Plain Picture#
Instead of writing a note that says "call the name method on whatever you're given", you just write the name of the method: "use name".
The Real Name#
A method reference is shorthand for a lambda that only calls one existing method. Four kinds:
| Kind | Syntax | Same as the 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 any object of a type | Student::name, String::trim | s -> s.name(), s -> s.trim() |
| constructor | ArrayList::new | () -> new ArrayList<>() |
students.stream().map(Student::name) // each student → its name
list.forEach(System.out::println) // print each
count.merge(word, 1, Integer::sum) // (a, b) -> a + b (07_java_collections_internals.md Ch 4)
Comparator.comparingInt(Student::score) // (07 Ch 7)Use a method reference when it's clearer; use a lambda when the logic is more than one call. s -> s.score() >= 150 has no method-reference form.
Check yourself
2 questionsWrite the lambda equivalent of String::length and HashMap::new.
Show answerHide answer
s -> s.length(); () -> new HashMap<>().
What does Student::name mean inside map(...)?
Show answerHide answer
"For each student, call its name() method" — a function from Student to String.