简体   繁体   English

如何使用 Stream.flatmap 将被展平的对象与展平的对象结合起来

[英]How do I combine the object being flattened with the flattened objects using Stream.flatmap

I have a stream of the following class:我有以下课程的流:

class A {
    Stream<B> bs;
}

and I want to convert it to a stream of the following class:我想将其转换为以下类的流:

class AB {
    A a;
    B b;
    AB(A a, B b) {
        this.a = a;
        this.b = b;
    }
}

I can see that flatMap will give me a stream of B:我可以看到flatMap会给我一个 B 流:

astream.flatMap(a -> a.bs);

but I can't figure out how to pass the a object through to a map like:但我不知道如何将对象传递到地图,例如:

astream.flatMap(a -> a.bs).map(b -> new AB(a, b));

If I try this I get an error:如果我尝试这个,我会收到一个错误:

error: cannot find symbol

which I sort of expected.我有点期待。

You have to map the B s of the bs Stream to AB s using map :你必须映射B S中的bs StreamAB S使用map

List<AB> abs = astream.flatMap(a -> a.bs.map(b->new AB(a,b)))
                      .collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM