Java 17 Recipes


-3. Invoking Existing Methods by Name


Download 3.2 Mb.
Pdf ko'rish
bet116/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   112   113   114   115   116   117   118   119   ...   245
Bog'liq
Java 17 Recipes

6-3. Invoking Existing Methods by Name
 Problem
You are developing a lambda expression that merely invokes a method that already exists 
in the object being passed to the lambda. Rather than write out the entire ceremony to 
invoke the method, you’d like to utilize a minimal amount of code.
 Solution
Rather than writing a lambda expression, use a method reference to call an existing 
method. In the following scenario, the Player object contains a static method 
named compareByGoal(), which takes two Player objects and compares the number 
of goals each contains. It then returns an integer representing the outcome. The 
compareByGoal() method is the same as Comparator.
public class Player {
private String firstName ;
private String lastName ;
private String position ;
private int status = -1;
private int goals;
public Player(){
}
public Player(String position, int status){
this.position = position;
this.status = status;
}
public String findPlayerStatus(int status){
String returnValue = null;
switch(status){
ChapTer 6 LaMbda expressIons


215
case 0:
returnValue = "ACTIVE";
case 1:
returnValue = "INACTIVE";
case 2:
returnValue = "INJURY";
default:
returnValue = "ON_BENCH";
}
return returnValue;
}
public String playerString(){
return getFirstName() + " " + getLastName() + " - " + 
getPosition();
}
// ** getters and setters removed for brevity **
/**
* Returns a positive integer if Player A has more goals than Player B
* Returns a negative integer if Player A has fewer goals than Player B
* Returns a zero if both Player A and Player B have the same number 
of goals
*/
public static int compareByGoal(Player a, Player b){
int eval;
if(a.getGoals() > b.getGoals()){
eval = 1;
} else if (a.getGoals() < b.getGoals()){
eval = -1;
} else {
eval = 0;
}
return eval;
}
}
ChapTer 6 LaMbda expressIons


216
The Player.compareByGoal() method could sort an array of Player objects. To 
do so, pass an array of Player objects (Player[]) to the Arrays.sort() method as the 
first argument, and pass a method reference Player::compareByGoal as the second 
argument. The result is a sorted list (in ascending order) of Player objects by the 
number of goals. The following line of code shows how to accomplish this task.
Arrays.sort(teamArray, Player::compareByGoal);

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   112   113   114   115   116   117   118   119   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling