[英]From Map<String, Set<Integer>> collect values from a Set<String> of keys
I am trying to use map to map a set of keys into a Map of String to Set of Integer.我正在尝试使用 map 到 map 一组键到 Map 到一组 ZA0FAEF0851B4294C44Z1B2 的字符串中。 Ideally I want to get all the value sets and collect them into a single set.
理想情况下,我想获取所有值集并将它们收集到一个集合中。
Lets say I have:可以说我有:
Map<String, List<Integer>> keyValueMap = new HashMap<>();
Set<String> keys = new HashSet<>();
Set<String> result = new HashSet<>();
I have tried:我努力了:
result.addAll(keys.stream().map(key -> keyValueMap.get(key)).collect(Collectors.toSet());
This nets me an error saying addAll() is not applicable for the type Set>.这给我带来了一个错误,说 addAll() 不适用于 Set> 类型。 I have tried replacing map() with flatMap() but I can't seem to get the syntax right if that is the solution.
我尝试用 flatMap() 替换 map() 但如果这是解决方案,我似乎无法正确使用语法。
What is the correct syntax to make this work?使这项工作的正确语法是什么?
Thanks!谢谢!
It looks like the type of result
should be Set<Integer>
instead of Set<String>
.看起来
result
的类型应该是Set<Integer>
而不是Set<String>
。
With your snippet, you're attempting to invoke Set#addAll
on a Set<Integer>
, but the argument being passed is a Set<List<Integer>>
, which doesn't compile.使用您的代码段,您尝试在
Set<Integer>
上调用Set#addAll
,但传递的参数是Set<List<Integer>>
,它不会编译。
To ameliorate your issue, one solution is to use flatMap
instead of map
:为了改善您的问题,一种解决方案是使用
flatMap
而不是map
:
result.addAll(keys.stream()
.flatMap(key -> keyValueMap.get(key).stream())
.collect(Collectors.toSet()));
A logically equivalent snippet is:一个逻辑上等价的片段是:
result.addAll(keys.stream()
.map(keyValueMap::get)
.flatMap(List::stream)
.collect(Collectors.toSet()));
Another solution would be to utilize Map#values
:另一种解决方案是利用
Map#values
:
result.addAll(keyValueMap.values().stream()
.flatMap(List::stream)
.collect(Collectors.toSet()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.