问题:
I have a Map<String, Set<String>>. I want all the values from this Map in a new Set<String> using the streams API. I was able to get a Set<Set<Strin...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I have a Map<String, Set<String>>
. I want all the values from this Map in a new Set<String>
using the streams API. I was able to get a Set<Set<String>>
, but what I want is all the values of all the sets from my map, in one Set. Is that possible using streams?
Thanks in advance.
回答1:
Here you go:
Set<String> allStrings = map.values()
.stream()
.flatMap(Set::stream)
.collect(Collectors.toSet());
回答2:
Another solution can be also :
Set<String> set = new HashSet<>();
map.values().forEach(set::addAll);
回答3:
You can use the Stream.collect()
method to achieve this:
Set<String> set = map.values().stream()
.collect(HashSet::new, HashSet::addAll, HashSet::addAll);
If you need to be more flexible you should use the Stream.flatMap()
solution.