如何将Set<Set<String>>转换为Set<String>?

假设Streams和Collections,Lambdas可以使用吗?我尝试使用 for 循环,但它没有解决我的问题。

// Set<Set<String>> to Set<String>
for(Set<String> s : set) {
    result.addAll(s);
    set.add(result);
}

set 是一种Set<Set<String>>类型, result 是Set<String>.

回答

这是使用 Stream API 的选项:

Set<String> result = sets.stream()
    .flatMap(Collection::stream)
    .collect(Collectors.toSet());

  • @GauthamM That’s a matter of taste. The method is declared in the `Collection` interface, so we need not know or care whether it’s `Set` or something else. I would probably do it the way you say, but I have no argument why it should be better or worse.

以上是如何将Set&lt;Set&lt;String&gt;&gt;转换为Set&lt;String&gt;?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>