-
拉丁的传说
基本上,您需要遍历地图的条目集,同时记住“当前已知的最大值”和与之相关的键。(当然,或者仅包含两者的条目。)例如:Map.Entry<Foo, Bar> maxEntry = null;for (Map.Entry<Foo, Bar> entry : map.entrySet()){ if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) { maxEntry = entry; }}
-
www说
为了完整起见,这是一种Java-8方式countMap.entrySet().stream().max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1).get().getKey();要么Collections.max(countMap.entrySet(), (entry1, entry2) -> entry1.getValue() - entry2.getValue()).getKey();要么Collections.max(countMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey();
-
米脂
该代码将打印所有具有最大值的键public class NewClass4 { public static void main(String[] args) { HashMap<Integer,Integer>map=new HashMap<Integer, Integer>(); map.put(1, 50); map.put(2, 60); map.put(3, 30); map.put(4, 60); map.put(5, 60); int maxValueInMap=(Collections.max(map.values())); // This will return max value in the Hashmap for (Entry<Integer, Integer> entry : map.entrySet()) { // Itrate through hashmap if (entry.getValue()==maxValueInMap) { System.out.println(entry.getKey()); // Print the key with max value } } }}