代码之家  ›  专栏  ›  技术社区  ›  Eric Lilja

从嵌套流中收集一组对象

  •  5
  • Eric Lilja  · 技术社区  · 6 年前

    我有一个场景,其中有两个for循环,一个嵌套在另一个内。在内部循环中,对于每个迭代,我都有创建特定类型的新实例所需的信息。我想将代码从for循环更改为使用流,以便将所有对象收集到一个ImmutableSet中。然而,我无法制作一个能够编译并工作的版本。下面的示例程序说明了我最近的尝试。它可以编译,但其中一个参数是硬编码的。

    如何修复下面的流,以便在分配Bar时,可以同时使用变量s和n?

    class Bar {
      private final String s;
      private final Integer n;
    
      Bar(String s, Integer n) {
        this.s = s;
        this.n = n;
      }
    }
    
    public class Foo {
    
      private static List<Integer> getList(String s) {
        return Lists.newArrayList(s.hashCode());
      }
    
      Foo() {
        ImmutableSet<Bar> set = ImmutableSet.of("foo", "bar", "baz")
                .stream()
                .flatMap(s -> getList(s).stream())
                .map(n -> new Bar("", n)) // I need to use s here, not hard-code
                .collect(ImmutableSet.toImmutableSet());
      }
    }
    
    1 回复  |  直到 6 年前
        1
  •  7
  •   Ousmane D.    6 年前

    似乎您正在寻找以下内容:

    .flatMap(s -> getList(s).stream().map(n -> new Bar(s, n)))
    

    简单地说,连锁另一个 map 操作到 getList(s).stream() 转换数据,从而使字符串和整数都在范围内。

    注意,您不仅限于 获取列表。流() 。这意味着只要函数传递给 flatMap 返回a Stream<R> 它将编译。