
假设我们有一个map<string, integer>,其中包含键值对。我们的目标是找到所有值等于map中最大值的键。
示例Map:
final Map<String, Integer> map = new HashMap<>();
map.put("first", 50);
map.put("second", 10);
map.put("third", 50);
map.put("fourth", 20);对于上述示例,Map中的最大值是50。键"first"和"third"都对应这个最大值。因此,我们期望的输出是一个包含["first", "third"]的列表。
现有尝试的局限性:
直接使用stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey)通常只能返回一个键,即使存在多个键拥有相同的最大值。例如,它可能返回"third"(取决于流的内部顺序),但会忽略"first"。这不符合我们收集所有最大值键的需求。
立即学习“Java免费学习笔记(深入)”;
此方法利用Java 8的Stream API进行多步处理。核心思想是首先根据值对Map的条目进行分组,然后从这些分组中找出与最大值对应的键列表。
实现思路:
代码示例:
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.*;
public class MaxKeysCollector {
public static List<String> getMaxKeysUsingStream(Map<String, Integer> map) {
return map.entrySet()
.stream()
// 步骤1: 按值分组。键是原始值,值是所有对应这些值的键的列表。
// 例如: {50=[first, third], 10=[second], 20=[fourth]}
.collect(groupingBy(Map.Entry::getValue, mapping(Map.Entry::getKey, toList())))
.entrySet()
.stream()
// 步骤2: 找出新Map中键(即原始最大值)最大的条目。
.max(Map.Entry.<Integer, List<String>>comparingByKey())
// 步骤3: 获取该条目的值,即包含所有最大值键的列表。
.orElseThrow(() -> new IllegalStateException("Map cannot be empty to find max keys."))
.getValue();
}
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); // 预期输出: [first, third] 或 [third, first] (顺序不保证)
}
}代码解析:
注意事项:
此方法涉及两次流迭代。第一次迭代用于分组,第二次迭代用于查找最大分组。虽然第二次迭代的Map通常会比原始Map小,但在数据量非常大的情况下,这可能会带来一定的性能开销。
对于追求极致性能的场景,一个传统的命令式循环通常是最高效的解决方案,因为它只需要对Map进行一次遍历。
实现思路:
代码示例:
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; // 初始化为最小值
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; // 更新最大值
}
// 如果 currentValue == maxValue,或者 currentValue > maxValue (清空后),则添加当前键
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);
map.put("fifth", 60); // 添加一个更大的值测试
List<String> maxKeysLoop = getMaxKeysUsingLoop(map);
System.out.println("命令式循环方法获取的最大值键列表: " + maxKeysLoop); // 预期输出: [fifth]
final Map<String, Integer> map2 = new HashMap<>();
map2.put("first", 50);
map2.put("second", 10);
map2.put("third", 50);
List<String> maxKeysLoop2 = getMaxKeysUsingLoop(map2);
System.out.println("命令式循环方法获取的最大值键列表 (原始示例): " + maxKeysLoop2); // 预期输出: [first, third]
}
}代码解析:
性能优势:
此方法只需要对Map进行一次迭代,因此在性能上通常优于Stream API的多步处理方法,尤其是在Map包含大量数据时。
本文提供了两种在Java 8中收集Map中所有具有相同最大值的键列表的方法:
在实际开发中,如果Map的数据量不是特别巨大,Stream API方法因其简洁性和声明性通常是更受欢迎的选择。但如果Map可能包含数十万甚至数百万条目,并且性能是首要考虑因素,那么单次迭代的命令式循环将是更明智的选择。
以上就是Java 8:如何收集Map中所有具有相同最大值的键列表的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号