有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

HashMap键集上的java迭代

我很难迭代hashmap并将具有最大整数的键集返回到hashmap中。。。我举个例子,谁能给我解释一下怎么做,谢谢

import java.util.*; 

public class Program {
    public static void main(String[ ] args) {
        HashMap <String, Integer> players = new HashMap<String, Integer>();
        players.put("Mario", 27);
        players.put("Luigi", 43);
        players.put("Jack", 11);
    
        //my problem goes here 
    
        for (HashMap.Entry <String, Integer> f : players.entrySet()) {
            System.out.println (Collections.max(f));
            /* 
            /usercode/Program.java:13: error: no suitable method found for 
            max(Entry<String,Integer>)
            System.out.println (Collections.max(f));
                                           ^
            method Collections.<T#1>max(Collection<? extends T#1>) is not applicable
            (cannot infer type-variable(s) T#1
            (argument mismatch; Entry<String,Integer> cannot be converted to Collection<? extends 
            T#1>))
            method Collections.<T#2>max(Collection<? extends T#2>,Comparator<? super T#2>) is not 
            applicable
            (cannot infer type-variable(s) T#2
            (actual and formal argument lists differ in length))
            where T#1,T#2 are type-variables:
            T#1 extends Object,Comparable<? super T#1> declared in method <T#1>max(Collection<? 
            extends T#1>)
            T#2 extends Object declared in method <T#2>max(Collection<? extends T#2>,Comparator<? 
            super T#2>)
            1 error */
        }
    }
}

我只需要打印按键集Luigi


共 (1) 个答案

  1. # 1 楼答案

    方法^{}需要一个Collection,并将返回其最大元素,在集合的内部元素上迭代。因此,没有必要在自己的代码中将其与循环结合起来

    当你的起点是一个Map而不是一个Collection时,你需要决定一个视图,keySet()entrySet()values()来传递给那个方法。因为您需要两者,比较的值和最终结果的键,^{}是正确的选择

    因为entrySet()的类型是Set<Map.Entry<String, Integer>>,换句话说,它是一个没有实现Comparable的元素集合,所以需要指定一个Comparator。接口Map.Entry已经提供了方便的内置比较器,比如^{},这正是您想要的

    所以,使用^{}的完整解决方案是

    System.out.println(
        Collections.max(players.entrySet(), Map.Entry.comparingByValue()).getKey()
    );
    

    当然,您也可以手动迭代entrySet(),并识别this answer中的最大元素