
在java开发中,我们经常需要处理键值对数据,例如map<string, integer>。一个常见的需求是找出所有具有最大值的键。例如,给定一个map:
final Map<String, Integer> map = new HashMap<>();
map.put("first", 50);
map.put("second", 10);
map.put("third", 50);我们期望的输出是["first", "third"],因为这两个键都关联着最大值50。
然而,初学者在使用Java 8 Stream API时,可能会尝试以下方法:
获取单个最大值键:
final String maxKey = map.entrySet()
.stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse(null);
System.out.println(maxKey); // 输出可能是 "third" (取决于Stream内部顺序)这种方法只会返回一个具有最大值的键,因为它在遇到第一个最大值时可能就完成了比较,无法收集所有相同最大值的键。
立即学习“Java免费学习笔记(深入)”;
按值降序排序所有键:
final List<String> keysInDescending = map.entrySet()
.stream()
.sorted(Map.Entry.<String,Integer>comparingByValue().reversed())
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println(keysInDescending); // 输出: [third, first, second]这种方法虽然能将所有键按值降序排列,但仍需要进一步处理才能提取出所有最大值对应的键,效率不高且不直观。
显然,以上方法都无法直接满足获取所有最大值键的需求。接下来,我们将介绍两种有效的解决方案。
此方法利用Stream API的强大功能,通过两次Stream操作实现目标。核心思想是首先将Map中的Entry按值进行分组,得到一个Map<Integer, List<String>>,其中键是原始值,值是所有具有该值的键列表。然后,从这个分组后的Map中找出键(即原始值)最大的那个Entry,其值就是我们所需的最大值键列表。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;
public class MaxKeysCollector {
public static List<String> getMaxKeysUsingStream(Map<String, Integer> map) {
if (map == null || map.isEmpty()) {
return new ArrayList<>(); // 或抛出异常,根据业务需求
}
return map.entrySet()
.stream()
// 步骤1: 按值分组,将相同值的键收集到列表中
// 结果是 Map<Integer, List<String>>,例如 {10=[second], 50=[first, third]}
.collect(groupingBy(Map.Entry::getValue, mapping(Map.Entry::getKey, toList())))
.entrySet()
.stream()
// 步骤2: 从分组后的Map中,找出键(即原始值)最大的那个Entry
.max(Map.Entry.comparingByKey())
// 如果Map为空或分组后为空,则抛出异常或返回默认值
.orElseThrow(() -> new IllegalStateException("Map should not be empty"))
.getValue(); // 获取该最大值Entry的值,即所有最大值对应的键列表
}
public static void main(String[] args) {
final Map<String, Integer> map = new HashMap<>();
map.put("first", 50);
map.put("second", 10);
map.put("third", 50);
map.put("fourth", 20);
List<String> maxKeys = getMaxKeysUsingStream(map);
System.out.println("Stream API 结果: " + maxKeys); // 输出: Stream API 结果: [first, third] (顺序可能不同)
}
}代码解析:
注意事项:
对于追求极致性能的场景,或者在Java 8以下版本,传统的for循环方法可能更优,因为它只需要一次迭代即可完成任务。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MaxKeysCollector {
public static List<String> getMaxKeysUsingLoop(Map<String, Integer> map) {
List<String> maxKeys = new ArrayList<>();
int maxValue = Integer.MIN_VALUE; // 初始化最大值为整型最小值
if (map == null || map.isEmpty()) {
return maxKeys;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
int currentValue = entry.getValue();
String currentKey = entry.getKey();
// 如果当前值小于已知的最大值,则跳过
if (currentValue < maxValue) {
continue;
}
// 如果当前值大于已知的最大值,说明找到了新的最大值
// 此时需要清空之前收集的键,并更新最大值
if (currentValue > maxValue) {
maxKeys.clear(); // 清空旧的最大值键列表
maxValue = currentValue; // 更新最大值
}
// 如果当前值等于或大于已知的最大值,则将当前键添加到列表中
maxKeys.add(currentKey);
}
return maxKeys;
}
public static void main(String[] args) {
final Map<String, Integer> map = new HashMap<>();
map.put("first", 50);
map.put("second", 10);
map.put("third", 50);
map.put("fourth", 20);
List<String> maxKeys = getMaxKeysUsingLoop(map);
System.out.println("传统循环 结果: " + maxKeys); // 输出: 传统循环 结果: [first, third] (顺序可能不同)
}
}代码解析:
性能优势:
| 特性 | Stream API (groupingBy) | 传统循环 (for-loop) |
|---|---|---|
| 可读性 | 声明式,简洁,符合函数式编程风格 | 命令式,逻辑清晰,易于理解每一步操作 |
| 性能 | 两次迭代(一次Map Entry,一次分组后的Map Entry),通常足够高效 | 单次迭代,在处理大量数据时通常具有最佳性能 |
| 复杂性 | 需要理解groupingBy和mapping等Collectors的用法 | 基础循环和条件判断,对Java开发者普遍熟悉 |
| 适用场景 | 倾向于函数式编程风格,对代码简洁性有要求,数据量适中 | 对性能有严格要求,处理超大数据集,或在旧Java版本中 |
选择建议:
理解这两种方法及其优缺点,能帮助开发者根据具体的项目需求和性能考量,做出明智的技术选择。
以上就是Java 8+:高效获取Map中所有最大值对应的键列表的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号