Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading