如何访问HashMap中的特定值

  • 本文关键字:HashMap 何访问 访问 java
  • 更新时间 :
  • 英文 :


这个简单的游戏要求玩家的数量和他们的名字,并计算他们的分数。我怎样才能得到得分最高的选手?

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

这就是我自己尝试的:

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

您可以使用Collections.max()获取HashMap.entrySet()获得的哈希图条目集合的最大值,并使用自定义比较器进行值比较。

示例:

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

您可以修改上面的代码以最好地满足您的条件。

最新更新