Search code examples
javajava-8java-stream

How to flatmap a stream of streams in Java?


I want to transform the stream of streams of objects to a single stream of objects. I know that I have to use the flatMap method, but I'm not able to achieve that, look at:

Stream<Stream<Object>> objectStreams = ...
Stream<Object> flatMappedStream = objectStreams.flatMap( ... );

Could anyone please help me?


Solution

  • Basically, you want to concatenate all the nested streams into one flat stream, without affecting the members themselves. You'll use

    objectStreams.flatMap(Function.identity());
    

    because you must provide some mapping function for each stream member, and in this case it is the identity function.


    Usually we end up with the nested streams because we apply a function that maps an item to a stream:

    Stream<Stream<Object>> objectStreams = srcStream.map(itemToStreamFunction);
    

    If this is your case, just change map to flatMap:

    Stream<Object> flatMappedStream = srcStream.flatMap(itemToStreamFunction);