【问题标题】:How to merge set use java stream with one line of code如何将集合使用java流与一行代码合并
【发布时间】:2020-11-30 18:52:57
【问题描述】:

我有两个这样的Set:

Set<String> set1;
Set<String> set2;

我想把它合并

Set<String> s = Stream.of(set1, set2).collect(Collectors.toSet());

和这样的错误:

enter image description here

如何使用 flatMap 将 Set 转换为一系列 String 对象? 有没有其他解决方案可以优雅地完成这个操作?

【问题讨论】:

  • 您需要将集合流扁平化为字符串流
  • 你为什么需要一个流?您是否尝试过使用addAll() 方法?

标签: java merge java-stream


【解决方案1】:

如果你坚持使用Streams,可以使用flatMap将你的Stream&lt;Set&lt;String&gt;&gt;转换成Stream&lt;String&gt;,可以收集成Set&lt;String&gt;

Set<String> s = Stream.of(set1, set2).flatMap(Set::stream).collect(Collectors.toSet());

【讨论】:

    【解决方案2】:

    您可以使用Stream.concat将两个集合的流合并并作为集合收集。

    Set<String> s = Stream.concat(set1.stream(), set2.stream()).collect(Collectors.toSet());
    

    【讨论】:

      【解决方案3】:

      有几种可能的方法-

      连接

      Set<String> s = Stream.concat(set1.stream(), set2.stream()).collect(Collectors.toSet());
      

      因为我们必须编写超过 2 个流,所以它有点难看

      Stream.concat(Stream.concat(set1.stream(), set2.stream()), set3.stream())
      

      连接可能是深度连接流的问题。来自文档 -

      从重复构造流时要小心 连接。访问深度连接流的元素可以 导致深度调用链,甚至 StackOverflowException。

      减少

      Reduce 也可用于执行流的串联 -

      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());
      

      与深度接触流相关的问题也适用于 reduce

      平面图

      Flatmap 可用于获得与 -

      相同的结果
       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());
      

      平面图避免StackOverflowException

      【讨论】:

      • 如果忽略 StackOverflowException 的风险,concat() 是否比 flatMap() 提供任何好处?
      猜你喜欢
      • 1970-01-01
      • 2015-10-20
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      • 2012-10-03
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      相关资源
      最近更新 更多