Java Reference
In-Depth Information
We now describe another feature that you'll see in Java 8 code: method references . Think of
them as shorthand versions of certain lambdas.
3.6. Method references
Method references let you reuse existing method definitions and pass them just like lambdas. In
some cases they appear more readable and feel more natural than using lambda expressions.
Here's our sorting example written with a method reference and a bit of help from the updated
Java 8 API (we explore this example in more detail in section 3.7 ):
Before:
inventory.sort((Apple a1, Apple a2)
-> a1.getWeight().compareTo(a2.getWeight()));
After (using a method reference and java.util.Comparator.comparing):
3.6.1. In a nutshell
Why should you care about method references? Method references can be seen as shorthand for
lambdas calling only a specific method. The basic idea is that if a lambda represents “call this
method directly,” it's best to refer to the method by name rather than by a description of how to
call it. Indeed, a method reference lets you create a lambda expression from an existing method
implementation. But by referring to a method name explicitly, your code can gain better
readability . How does it work? When you need a method reference, the target reference is
placed before the delimiter :: and the name of the method is provided after it. For example,
Apple::getWeight is a method reference to the method getWeight defined in the Apple class.
Remember that no brackets are needed because you're not actually calling the method. The
method reference is shorthand for the lambda expression (Apple a) -> a.getWeight(). Table 3.4
gives a couple more examples of possible method references in Java 8.
Search WWH ::




Custom Search