如何使用Java流API过滤地图? [英] How to filter a map with Java stream api?
本文介绍了如何使用Java流API过滤地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Map<Integer, String> map = new HashMap<>();
map.put(1, "f");
map.put(2, "i");
map.put(3, "a");
map.put(4, "c");....etc
现在我有一个列表:
List<Integer> picks = {1,3}
我想取回一个字符串列表,即映射中与"pick"列表中的键值匹配的值.因此,我希望取回{"f",结果" .有没有一种方法可以使用 java流api 以一种优雅的方式做到这一点?
I would like to get back a list of Strings, ie, values from map that matches the key values, found in the 'pick' list.So, I am expecting to get back {"f", "a"} as result. Is there a way to use java stream api to do it in elegant way?
当有一个值时,我就是这样:
When there is one value , I am doing it this way:
map.entrySet().stream()
.filter(entry -> "a".equals(entry.getValue()))
.map(entry -> entry.getValue())
.collect(Collectors.toList())
但是在要筛选的键/小贴士列表时会变得很困难.
But getting hard time when there is a list of keys/picks to filter with.
推荐答案
您可以在Stream#filter
中使用List.contains()
来仅接受列表中存在的那些值:
You can use List.contains()
in the Stream#filter
to only accept those values which are present in the list:
List<String> result = map.entrySet()
.stream()
.filter(ent -> picks.contains(ent.getKey()))
.map(Map.Entry::getValue)
.collect(Collectors.toList());
这篇关于如何使用Java流API过滤地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文