Video in progress
What kinds of method references are there? Give an example of each.
Four kinds: to a static method (Integer::parseInt), to a method of a specific object (System.out::println), to a method of an arbitrary object (String::toUpperCase) and to a constructor (ArrayList::new).
📖 Answer
A method reference is a shorter way to write a lambda that only calls one existing method.
// 1. static method
Function<String, Integer> parse = Integer::parseInt; // s -> Integer.parseInt(s)
// 2. method of a specific object
PrintStream out = System.out;
Consumer<String> print = out::println; // s -> out.println(s)
// 3. method of an arbitrary object (the first parameter is that object)
Function<String, String> upper = String::toUpperCase; // s -> s.toUpperCase()
BiPredicate<String, String> eq = String::equalsIgnoreCase; // (a, b) -> a.equalsIgnoreCase(b)
// 4. constructor
Supplier<List<String>> listMaker = ArrayList::new; // () -> new ArrayList<>()
Type 3 is where people get confused in interviews. String::toUpperCase is not static, but it is written like a static one. Here the element coming from the stream is itself this.
When it's better to stay with a lambda: if you need to transform the arguments or add some extra logic (s -> s.trim().toLowerCase()). Forcing a reference makes the code harder to read.
Sign up to mark studied questions and save your progress.