I am trying to beat a sololearn challenge where we store the name of a player in a hashmap and then I am needed to iterate through the values of each player hashmap and get the name of the player with the highest score. I have been given a template code but do not have any idea on how to complete the class Bowling with a method called getWinner() to get the name of the player with the maximum points please help
import java.util.*;
public class Bowling {
HashMap<String, Integer> players;
Bowling() {
players = new HashMap<String, Integer>();
}
public void addPlayer(String name, int p) {
players.put(name, p);
}
//your code goes here
void getWinner(){
//help me complete this to get the name or the winner
}
}
public class Program {
public static void main(String[ ] args) {
Bowling game = new Bowling();
Scanner sc = new Scanner(System.in);
for(int i=0;i<3;i ) {
String input = sc.nextLine();
String[] values = input.split(" ");
String name = values[0];
int points = Integer.parseInt(values[1]);
game.addPlayer(name, points);
}
game.getWinner();
}
}
CodePudding user response:
You get the entrySet
(key, value), use a Comparator
and compare them by the value and use Collections.max()
to get the highest value. After this just get the key and you have the player name:
Collections.max(players.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey();