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 的最佳方法是什么?


基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01