Java Reference
In-Depth Information
Arrays.sort(teamArray, Player::compareByGoal);
How It Works
Consider that your lambda expression is going to invoke a single method by name, per-
haps returning a result. If a lambda expression fits this scenario, it is a prime candidate
for use with a method reference. A method reference is a simplified form of a lambda
expression, which specifies the class name or instance name, followed by the method
to be called in the following format:
<class or instance name>::<methodName>
The double colon ( :: ) operator specifies a method reference. Since a method refer-
ence is a simplified lambda method, it must implement a functional interface, and the
abstract method within the interface must have the same argument list and return type
as the method being referenced. Any arguments are subsequently derived from the con-
text of the method reference. For instance, consider the same scenario as the solution,
whereby you wanted to sort an array of Player objects by calling upon the Play-
er.compareByGoal() method to perform goal comparisons. The following code
could be written to enable this functionality via a lambda expression:
Arrays.sort(teamArray, (p1, p2) ->
Player.compareByGoal(p1,p2));
In this code, the array is passed as the first argument to Arrays.sort() , and the
second argument is a lambda expression that passes two Player objects to the
Player.compareByGoal() method. The lambda expression uses the functional
interface Comparator<Player>.compare , which utilizes the (Player,
Player) parameter list. The compareByGoal() method contains that same para-
meter list. Likewise, the return type of compareByGoal() matches the return type
within the functional interface. Therefore, the parameter list does not need to be speci-
fied in the listing; it can be inferred from the context of the method reference Play-
er::compareByGoal instead.
There are four different types of method references, and Table 6-2 lists each of
them.
Table 6-2 . Method Reference Types
 
 
Search WWH ::




Custom Search