what is the best way to get a sub HashMap based on a list of Keys?(根据键列表获取子 HashMap 的最佳方法是什么?)
问题描述
我有一个 HashMap,我想获得一个新的 HashMap,它只包含第一个 HashMap 中的元素,其中 K 属于特定列表.
I have a HashMap and I would like to get a new HashMap that contains only the elements from the first HashMap where K belongs to a specific List.
我可以查看所有键并填充一个新的 HashMap,但我想知道是否有更有效的方法来做到这一点?
I could look through all the keys and fillup a new HashMap but I was wondering if there is a more efficient way to do it?
谢谢
推荐答案
使用 Java8 流,有一个功能性(优雅)的解决方案.如果 keys
是要保留的键列表,而 map
是源 Map
.
With Java8 streams, there is a functional (elegant) solution. If keys
is the list of keys to keep and map
is the source Map
.
keys.stream()
.filter(map::containsKey)
.collect(Collectors.toMap(Function.identity(), map::get));
完整示例:
List<Integer> keys = new ArrayList<>();
keys.add(2);
keys.add(3);
keys.add(42); // this key is not in the map
Map<Integer, String> map = new HashMap<>();
map.put(1, "foo");
map.put(2, "bar");
map.put(3, "fizz");
map.put(4, "buz");
Map<Integer, String> res = keys.stream()
.filter(map::containsKey)
.collect(Collectors.toMap(Function.identity(), map::get));
System.out.println(res.toString());
打印:{2=bar, 3=fizz}
EDIT为地图中不存在的键添加一个过滤器
EDIT add a filter
for keys that are absent from the map
这篇关于根据键列表获取子 HashMap 的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:根据键列表获取子 HashMap 的最佳方法是什么?


- C++ 和 Java 进程之间的共享内存 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01