从嵌套流中收集一组对象

Eri*_*lja 4 java guava java-8 java-stream

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

Ous*_* D. 6

好像你正在寻找以下方面的东西:

.flatMap(s -> getList(s).stream().map(n -> new Bar(s, n)))
Run Code Online (Sandbox Code Playgroud)

简单地说,链接另一个map操作来getList(s).stream()转换数据,从而使你能够在范围内同时拥有字符串和整数.

请注意,您不仅限于此getList(s).stream().意思是只要传递给函数flatMap返回Stream<R>它就会编译,就可以将所有复杂操作链接在一起.