Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatmap a stream of streams in Java? [duplicate]

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?

like image 252
winklerrr Avatar asked Aug 13 '15 15:08

winklerrr


People also ask

What is flatMap in Java streams?

Stream flatMap(Function mapper) returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Stream flatMap(Function mapper) is an intermediate operation. These operations are always lazy.

Can we use same stream twice?

From the documentation: A stream should be operated on (invoking an intermediate or terminal stream operation) only once. A stream implementation may throw IllegalStateException if it detects that the stream is being reused. So the answer is no, streams are not meant to be reused.

How do I combine two streams in Java?

concat() in Java. Stream. concat() method creates a concatenated stream in which the elements are all the elements of the first stream followed by all the elements of the second stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel.


1 Answers

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.

like image 151
Marko Topolnik Avatar answered Sep 17 '22 00:09

Marko Topolnik