迭代 HashMap 的键集

Iteration on keyset of HashMap

我很难将 hashmap 和 return 具有最大整数的键集迭代到 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。

您可以尝试通过像这样迭代条目集来手动找到最大值

HashMap.Entry<String, Integer> maxEntry = new AbstractMap.SimpleEntry<String, Integer>("temp", -1);
for(HashMap.Entry<String, Integer> entry : players.entrySet()) {
    if(entry.getValue() > maxEntry.getValue()) {
        maxEntry = entry;
    }
}
System.out.println(maxEntry);

条目是一对值:键和值。

当您迭代 Map 时,您会在迭代中获得下一个条目,因此您可以通过 getValue() 方法从条目中获取值并将其与临时变量 (maxEntry) 中的现有值进行比较。

您可以从 Entry 获取值以格式化输出,例如:

System.out.println("Name: " + maxEntry.getKey() + " Age: " + maxEntry.getValue());

页。秒。抱歉我的英语不好

方法 Collections.max(…) 需要一个 Collection 并将 return 它的最大元素,在内部迭代集合的元素。因此,您无需在自己的代码中将其与循环结合使用。

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

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

因此,使用 Collections.max(…) 的完整解决方案是

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

当然,您也可以像.

那样手动遍历entrySet()并确定最大元素