如何高效获取HashMap<String, Integer>中最大值对应的键?
获取HashMap中最大值对应键的高效方法
针对你的需求,这里提供几种实用且高效的实现方式,覆盖基础遍历到Java 8+的简洁写法,你可以根据场景选择:
1. 基础遍历(最优性能,无额外依赖)
直接遍历HashMap的键值对集合,手动记录最大值和对应键,时间复杂度O(n)(n为map中键值对数量),是最直接高效的方案:
public String most(String[] sentences) { HashMap<String, Integer> wordFreq = new HashMap<>(); for(String sentence : sentences) { String[] words = sentence.split(" "); for (String word : words) { wordFreq.merge(word, 1, Integer::sum); } } String maxKey = null; int maxValue = -1; for (Map.Entry<String, Integer> entry : wordFreq.entrySet()) { if (entry.getValue() > maxValue) { maxValue = entry.getValue(); maxKey = entry.getKey(); } // 若需保留最后一个出现的最大频率键,将判断条件改为 >= } return maxKey; }
注意:如果存在多个键对应相同最大频率,此方法会返回第一个遍历到的键。
2. Java 8+ 流操作(代码更简洁)
利用Stream API实现,性能和基础遍历接近,代码可读性更高:
public String most(String[] sentences) { HashMap<String, Integer> wordFreq = new HashMap<>(); for(String sentence : sentences) { String[] words = sentence.split(" "); for (String word : words) { wordFreq.merge(word, 1, Integer::sum); } } return wordFreq.entrySet() .stream() .max(Map.Entry.comparingByValue()) .map(Map.Entry::getKey) .orElse(null); }
说明:max()返回Optional类型,用orElse(null)处理map为空的情况(比如输入sentences数组为空时);若存在多个最大频率键,返回结果取决于HashMap的遍历顺序。
3. 统计时实时跟踪最大值(减少一次遍历)
如果追求极致效率,可以在统计词频的同时就跟踪当前最大频率和对应键,省去后续单独遍历map的步骤:
public String most(String[] sentences) { HashMap<String, Integer> wordFreq = new HashMap<>(); String maxKey = null; int maxValue = -1; for(String sentence : sentences) { String[] words = sentence.split(" "); for (String word : words) { // 更新当前词的频率 int currentFreq = wordFreq.merge(word, 1, Integer::sum); // 实时检查是否超过当前最大值 if (currentFreq > maxValue) { maxValue = currentFreq; maxKey = word; } // 若需保留最后一个出现的最大频率键,将判断条件改为 >= } } return maxKey; }
内容的提问来源于stack exchange,提问作者Michael Scutari
相关产品推荐
相关产品推荐

