Having a map of Set in Java 8, how I can put all the values in one set?

问题: 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.

  • 发表于 2019-03-29 22:36
  • 阅读 ( 213 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除