Java 相关,用 list 去匹配 map 的 key,返回 map 的 value 的用法?

2023-01-16 14:45:04 +08:00
 cencoroll

请问 java 中有没有 stream 的方法或者使用别的算法之类的去完成这个逻辑?

我有: List<String> list; Map<String, Integer> keyMap;

如果 list 的值命中 keyMap 里的 key 了,就返回一个 List<Integer> valueList 这样

822 次点击
所在节点    问与答
5 条回复
Nooooobycat
2023-01-16 14:55:24 +08:00
list.stream().map(keyMap::get).collect(Collectors.toList());

这样可以吗
superedlimited
2023-01-16 14:59:55 +08:00
map.keyset().filter(el -> list.include(el)).map(el -> keyMap.get(el))
Leviathann
2023-01-16 15:09:49 +08:00
list
filter get from map not null
map
issakchill
2023-01-16 15:18:15 +08:00
public <T> List<T> getByKeyList(Map<Integer, T> map, List<Integer> idList) {
if (CollectionUtil.isEmpty(map) || CollectionUtil.isEmpty(idList)) {
return new ArrayList<>();
}

return idList.stream()
.map(map::get)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
cencoroll
2023-01-17 09:24:39 +08:00
@Nooooobycat
@superedlimited
@Leviathann
@issakchill
感谢,昨天改 bug 改得头大,脑子转不过来了。谢谢大佬们!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/909273

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX