3 回答

TA貢獻1789條經(jīng)驗 獲得超8個贊
基本上,您需要遍歷地圖的條目集,同時記住“當前已知的最大值”和與之相關(guān)的鍵。(當然,或者僅包含兩者的條目。)
例如:
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條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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
}
}
}
}
添加回答
舉報