简体   繁体   中英

How to get the player with maximum points in a Java hashmap

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();
    }
}

You can get all key from a map with keySet() and so get the values associated to the key. So here a key would be the name of a player and the values is score. So here is a simple answer if there is no tie:).

        void getWinner(){
        int currentBestScore = 0;
        String currentWinner = "nobody"
        for ( String playerName : players.keySet() ) {
            if(players.get(playerName)>=currentBestScore){
                 currentWinner = playerName;
            }
        }
        System.out.println(playerName);
}

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM