在Java映射中查找与最大值关联的键

获取与映射中的最大值关联的键的最简单方法是什么?


我相信,当您想要对应于最大值的键时,Collections.max(someMap)将返回最大键。


明月笑刀无情
浏览 425回答 3
3回答

拉丁的传说

基本上,您需要遍历地图的条目集,同时记住“当前已知的最大值”和与之相关的键。(当然,或者仅包含两者的条目。)例如:Map.Entry<Foo, Bar> maxEntry = null;for (Map.Entry<Foo, Bar> entry : map.entrySet()){&nbsp; &nbsp; if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; maxEntry = entry;&nbsp; &nbsp; }}

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 {&nbsp; &nbsp; public static void main(String[] args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; HashMap<Integer,Integer>map=new HashMap<Integer, Integer>();&nbsp; &nbsp; &nbsp; &nbsp; map.put(1, 50);&nbsp; &nbsp; &nbsp; &nbsp; map.put(2, 60);&nbsp; &nbsp; &nbsp; &nbsp; map.put(3, 30);&nbsp; &nbsp; &nbsp; &nbsp; map.put(4, 60);&nbsp; &nbsp; &nbsp; &nbsp; map.put(5, 60);&nbsp; &nbsp; &nbsp; &nbsp; int maxValueInMap=(Collections.max(map.values()));&nbsp; // This will return max value in the Hashmap&nbsp; &nbsp; &nbsp; &nbsp; for (Entry<Integer, Integer> entry : map.entrySet()) {&nbsp; // Itrate through hashmap&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (entry.getValue()==maxValueInMap) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(entry.getKey());&nbsp; &nbsp; &nbsp;// Print the key with max value&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java