Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Flatmap() method preserve the order of the streams? [duplicate]

Tags:

java

java-8

I need to concatenate multiple integer array and preserve the order of elements while I am doing it.

For instance;

 final Integer[] arr1= { 1, 3, 2 };
 final Integer[] arr2= { 4, 6, 5 };
 final Integer[] arr3= { 7, 9, 8, 10 };
 final Integer[] arr4= { 11, 13, 12, 15, 14 };

So when I try to combine those 4 arrays into one array using Java 8 streams;

Stream.of(arr1, arr2, arr3, arr4).flatMap(Stream::of).toArray(Integer[]::new); 

This perfectly gives the results;

[1, 3, 2, 4, 6, 5, 7, 9, 8, 10, 11, 13, 12, 15, 14]

However, I read some articles and comments around and people claim that flatMap method does not always preserve the order of the original stream. Is this correct? What else I can do to preserve the original order?

like image 915
Erdi İzgi Avatar asked Feb 23 '18 11:02

Erdi İzgi


People also ask

What does the flatMap () function do?

The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1 ( arr. map(... args).

What does flatMap do in stream?

flatMap. 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. Each mapped stream is closed after its contents have been placed into this stream.

What is true regarding stream map and flatMap methods?

Both map and flatMap can be applied to a Stream<T> and they both return a Stream<R> . The difference is that the map operation produces one output value for each input value, whereas the flatMap operation produces an arbitrary number (zero or more) values for each input value.

Does stream map maintain order?

A parallel stream is performed one or more elements at a time. Thus the map() would preserve the encounter of the stream order but not the original List's order.


1 Answers

Does flatmap() method preserve the order of the streams?

Yes, It does and map() also.

However, I read some articles and comments around and people claim that flatMap method does not always preserve the order of the original stream. Is this correct?

Without any real-life example, it would be very difficult to argue this.


Sources : zeroturnaround.com

enter image description here

like image 121
Mehraj Malik Avatar answered Oct 03 '22 19:10

Mehraj Malik