12

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?

Erdi İzgi
  • 1,262
  • 2
  • 15
  • 33
  • 3
    Why not use `concatMap` if the order is critical? – vahdet Feb 23 '18 at 11:28
  • Could you link some of these articles or comments? The Java docs say "If a stream is ordered, repeated execution of identical stream pipelines on an identical source will produce an identical result; if it is not ordered, repeated execution might produce different results.". – Lukas Körfer Feb 23 '18 at 11:35
  • 1
    Just a quick note on code snippets: Whether or not you have `final` in this example does not matter, so it would require less effort from the reader of this question if you removed it. And you probably don't need four arrays to illustrate your question either. I recommending keeping examples extra minimal, (even though this was *fairly* minimal, so that's good). – Christian Neverdal Feb 23 '18 at 11:38
  • 1
    *generally* unless an operation is specified in the documentation as `unordered`, it is ordered – Eugene Feb 23 '18 at 11:41
  • 1
    In my case `flatMap` is not preserving order so I used `concatMap` instead. @vahdet +1 for your comment. – malhobayyeb Mar 27 '20 at 23:43

1 Answers1

15

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

Mehraj Malik
  • 14,872
  • 15
  • 58
  • 85