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?
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).
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.
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.
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.
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
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