问题描述
我有两个这样的套装:
Set<String> set1;
Set<String> set2;
我想与之合并
Set<String> s = Stream.of(set1,set2).collect(Collectors.toSet());
和这样的错误:
如何使用flatMap将Set转换为String对象的序列? 还有其他解决方案可以优雅地完成此操作吗?
解决方法
如果您坚持使用Stream
,则可以使用flatMap
将Stream<Set<String>>
转换为Stream<String>
,然后将其收集到Set<String>
中:
Set<String> s = Stream.of(set1,set2).flatMap(Set::stream).collect(Collectors.toSet());
,
您可以使用Stream.concat
合并两组数据流并按组收集。
Set<String> s = Stream.concat(set1.stream(),set2.stream()).collect(Collectors.toSet());
,
可能有几种方法-
Concat
Set<String> s = Stream.concat(set1.stream(),set2.stream()).collect(Collectors.toSet());
要写两个以上的流,这有点难看
Stream.concat(Stream.concat(set1.stream(),set2.stream()),set3.stream())
对于深层连接的流,Concat可能是个问题。从文档-
从重复构造流时要谨慎 串联:访问深度串联流的元素可以 导致深层调用链,甚至导致StackOverflowException。
减少
Reduce也可用于--p
Set<String> s = Stream.of(set1.stream(),set2.stream()).reduce(Stream::concat)
.orElseGet(Stream::empty).collect(Collectors.toSet());
这里Stream.reduce(
)返回可选,这就是调用orElseGet
方法的原因。也可以联系多个设置为
Stream.of(set1.stream(),set2.stream(),set2.stream()).reduce(Stream::concat).orElseGet(Stream::empty).collect(Collectors.toSet());
与深度联系流相关的问题也同样适用于减少
平面图
平面图可用于获得与-
相同的结果 Set<String> s = Stream.of(set1,set2).flatMap(Set::stream).collect(Collectors.toSet());
要连接多个流,可以使用-
Set<String> s = Stream.of(set1,set2,set3).flatMap(Set::stream).collect(Collectors.toSet());
flatmap避免使用StackOverflowException
。