
在 java 开发中,我们经常需要处理键值对数据结构,例如 map<string, integer>。一个常见的需求是找出所有映射到最大值的键。例如,给定一个 map:
final Map<String, Integer> map = new HashMap<>();
map.put("first", 50);
map.put("second", 10);
map.put("third", 50);我们期望的输出是一个包含所有最大值键的 List,即 ["first", "third"],因为 "first" 和 "third" 都对应着最大值 50。
初学者可能会尝试使用 Stream API 的 max 方法,但这种方法通常只能返回一个最大值对应的键(如果存在多个,则返回其中一个):
// 只能获取一个最大值对应的键
final String maxKey = map.entrySet()
.stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse(null);
System.out.println(maxKey); // 可能会输出 "third" 或 "first",取决于内部迭代顺序或者尝试对所有条目按值降序排序,但这会返回所有键,而不是仅限于最大值对应的键:
// 返回所有键,按值降序排列
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]这些方法都无法直接满足获取所有最大值键的需求。
立即学习“Java免费学习笔记(深入)”;
此方法利用 Stream API 的强大功能,通过两次迭代实现。第一次迭代将所有键按其值进行分组,第二次迭代则从分组后的 Map 中找出最大值对应的键列表。
import java.util.List;
import java.util.Map;
import java.util.HashMap;
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> getMaxKeysUsingStreams(Map<String, Integer> map) {
if (map == null || map.isEmpty()) {
return List.of(); // 返回空列表或抛出异常,取决于业务需求
}
return map.entrySet()
.stream()
// 1. 按值进行分组:Map<Integer, List<String>>
// 键是值(Integer),值是所有映射到该值的键列表(List<String>)
.collect(groupingBy(Map.Entry::getValue, mapping(Map.Entry::getKey, toList())))
.entrySet()
.stream()
// 2. 找到分组Map中键(即原始值)最大的那个条目
.max(Map.Entry.comparingByKey())
// 3. 如果Map为空,orElseThrow()会抛出NoSuchElementException。
// 更好的做法是处理Optional为空的情况,例如返回一个空列表。
.orElseThrow(() -> new IllegalStateException("Map is empty or contains no entries."))
// 4. 获取该最大条目中的值,即对应的键列表
.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", 30);
List<String> maxKeys = getMaxKeysUsingStreams(map);
System.out.println("Stream API 方案结果: " + maxKeys); // 输出: Stream API 方案结果: [first, third] (顺序可能不同)
}
}解析:
优点: 代码简洁、声明式风格,易于理解其意图。 缺点: 进行了两次迭代,对于非常大的 Map 可能会有轻微的性能开销,但通常情况下影响不大。
对于性能要求极高的场景,或者当 Map 包含大量数据时,单次迭代的命令式 for 循环通常是最高效的。它在一次遍历中同时追踪当前的最大值和所有与该最大值关联的键。
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
public class MaxKeysCollectorOptimized {
public static List<String> getMaxKeysOptimized(Map<String, Integer> map) {
List<String> maxKeys = new ArrayList<>();
int maxValue = Integer.MIN_VALUE; // 初始化为Integer的最小值,确保任何Map值都能被正确比较
if (map == null || map.isEmpty()) {
return maxKeys; // 返回空列表
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
int currentValue = entry.getValue();
if (currentValue < maxValue) {
// 当前值小于已知的最大值,跳过
continue;
}
if (currentValue > maxValue) {
// 发现了一个新的更大的值
maxKeys.clear(); // 清空之前收集的键,因为它们不再是最大值
maxValue = currentValue; // 更新最大值
}
// 如果 currentValue == maxValue,则将当前键添加到列表中
// 如果 currentValue > maxValue,在清空后,也需要将当前键添加
maxKeys.add(entry.getKey());
}
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", 30);
List<String> maxKeys = getMaxKeysOptimized(map);
System.out.println("单次迭代优化方案结果: " + maxKeys); // 输出: 单次迭代优化方案结果: [first, third] (顺序可能不同)
}
}解析:
优点: 性能最佳,只需单次迭代。 缺点: 代码是命令式风格,相对于 Stream API 方案,可能在某些人看来可读性稍差。
Stream API 方案 (分组和筛选):
单次迭代优化方案:
在大多数现代 Java 应用中,Stream API 方案的性能开销通常可以忽略不计,因此可以优先选择其提供的简洁性和可读性。然而,如果经过性能分析发现 Stream API 成为瓶颈,那么单次迭代的优化方案将是更合适的选择。
本文介绍了在 Java 8+ 中获取 Map 中所有最大值对应的键列表的两种主要方法:一种是利用 Stream API 进行分组和筛选,另一种是采用单次迭代的命令式优化方案。两种方法都能正确解决问题,但在代码风格、性能和适用场景上各有侧重。开发者应根据项目的具体需求和性能考量,选择最适合的实现方式。
以上就是在 Java 8 中获取 Map 中所有最大值对应的键列表教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号