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?