gpt4 book ai didi

java - 基于键列表获取子 HashMap 的最佳方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 22:38:05 26 4
gpt4 key购买 nike

我有一个 HashMap,我想得到一个新的 HashMap,它只包含第一个 HashMap 中的元素,其中 K 属于特定列表。

我可以查看所有键并填充一个新的 HashMap,但我想知道是否有更有效的方法来做到这一点?

谢谢

最佳答案

有了 Java8 流,就有了一个功能性(优雅)的解决方案。如果 keys 是要保留的键列表,map 是源 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}

编辑 为 map 中不存在的键添加一个过滤器

关于java - 基于键列表获取子 HashMap 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28856781/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com