3 回答

TA贡献1789条经验 获得超8个赞
基本上,您需要遍历地图的条目集,同时记住“当前已知的最大值”和与之相关的键。(当然,或者仅包含两者的条目。)
例如:
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;
}
}

TA贡献1775条经验 获得超8个赞
为了完整起见,这是一种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();

TA贡献1836条经验 获得超3个赞
该代码将打印所有具有最大值的键
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
}
}
}
}
添加回答
举报