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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With