从嵌套流中收集对象集

Collect set of objects from nested streams

我有一个场景,我有两个 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());
  }
}

您似乎在寻找类似以下内容的内容:

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

只需将另一个 map 操作链接到 getList(s).stream() 即可转换数据,从而使您能够在范围内同时拥有字符串和整数。

请注意,您不仅限于 getList(s).stream()。这意味着只要函数传递给 flatMap returns a Stream<R> 它将编译,就可以将任意多的复杂操作链接在一起。