简体   繁体   中英

How can i access specific value in a HashMap?

This simple game asks for the number of the players and their names and counts their score.How can i get the player with the highest score?

main:

  public static void main(String[] args) {


    Scanner scanner = new Scanner(System.in);
    HashMap<String,Integer> players= new HashMap<String,Integer>();

    System.out.printf("Give the number of the players: ");
    int numOfPlayers = scanner.nextInt();

    for(int k=1;k<=numOfPlayers;k++)
    {
        System.out.printf("Give the name of player %d: ",k);
        String nameOfPlayer= scanner.next();
        players.put(nameOfPlayer,0);//score=0
    }

    //This for finally returns the score
    for(String name:players.keySet())
    {
          System.out.println("Name of player in this round: "+name);
          //::::::::::::::::::::::
          //::::::::::::::::::::::


          int score=players.get(name)+ p.getScore();;

          //This will update the corresponding entry in HashMap
          players.put(name,score);
          System.out.println("The Player "+name+" has "+players.get(name)+" points ");
    }
}

This what i tried myself:

Collection c=players.values(); 
System.out.println(Collections.max(c)); 

You can use Collections.max() to get the maximum value of the Collection of hashmap entries obtained by HashMap.entrySet() with custom comparator for comparing values.

Example:

    HashMap<String,Integer> players= new HashMap<String,Integer>();
    players.put("as", 10);
    players.put("a", 12);
    players.put("s", 13);
    players.put("asa", 15);
    players.put("asaasd", 256);
    players.put("asasda", 15);
    players.put("asaws", 5);
    System.out.println(Collections.max(players.entrySet(),new Comparator<Entry<String, Integer>>() {
        @Override
        public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
            return o1.getValue().compareTo(o2.getValue());
        }
    }));

You can modify above code to best meet your condition.

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