Java Reference
In-Depth Information
Table 3.4. Examples of lambdas and method reference equivalents
Lambda
Method reference equivalent
(Apple a) -> a.getWeight()
Apple::getWeight
() -> Thread.currentThread().dumpStack()
Thread.currentThread()::dumpStack
(str, i) -> str.substring(i)
String::substring
(String s) -> System.out.println(s)
System.out::println
You can think of method references as syntactic sugar for lambdas that refer only to a single
method because you write less to express the same thing.
Recipe for constructing method references
There are three main kinds of method references:
1
. A method reference to a
static method
(for example, the method parseInt of Integer, written
Integer::parseInt)
2
. A method reference to an
instance method of an arbitrary type
(for example, the method
length of a String, written String::length)
3
. A method reference to an
instance method of an existing object
(for example, suppose you
have a local variable expensiveTransaction that holds an object of type Transaction, which
supports an instance method getValue; you can write expensiveTransaction::getValue)
The second and third kinds of method references may be a bit overwhelming at first. The idea
with the second kind of method references such as String::length is that you're referring to a
method to an object that will be supplied as one of the parameters of the lambda. For example,
the lambda expression (String s) -> s.toUpperCase() can be rewritten as String::toUpperCase.
But the third kind of method references refers to a situation when you're calling a method in a
lambda to an external object that already exists. For example, the lambda expression () ->
expensiveTransaction.getValue() can be rewritten as expensiveTransaction::getValue.
The shorthand rules to refactor a lambda expression to an equivalent method reference follow
simple recipes, shown in
figure 3.5
.
Search WWH ::
Custom Search