2

Assume I have an infinite Stream.

IntStream istream = IntStream.iterate(0, i -> i + 1).limit(100);
Stream<Integer> boxedStream = istream.boxed();

Does the boxed() method preserve order? Probably yes, but I cannot find it in the documentation.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Łukasz Rzeszotarski
  • 5,791
  • 6
  • 37
  • 68
  • The Javadoc on `IntStream`, for instance, says that it returns `stream that is consistent of the elements of this stream, each boxed to an Integer`. I wouldn't expect it to change the order. Are you seeing a changed order? How? Maybe try using Stream::peek to find out? – Kedar Mhaswade Feb 26 '16 at 18:10
  • 1
    Question is a bit unclear, what do you mean by "order"? Everything is there: https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#Ordering although you might want to read the whole doc multiple times :). – Tunaki Feb 26 '16 at 18:51
  • I'm sure it does, but I cannot find any documentation indicating that it's guaranteed to do so. (I would have settled for documentation indicating that intermediate operations do not modify Spliterator flags unless specified as doing so, but I couldn't even find anything about that.) – VGR Feb 26 '16 at 20:38
  • Yes I think it does. Venkat Subramaniam wrote me on twitter that if not stated otherwise is not supposed to alter the order. – Łukasz Rzeszotarski Feb 26 '16 at 20:41

1 Answers1

3

Actually every intermediate operation preserves an order by default. The only exceptions are:

  • unordered() which removes the ordering constraint.
  • sorted() which changes the order.

When it's not explicitly specified, you can assume that operation keeps the order. Even distinct() keeps the order, though it adds much complexity for parallel stream.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334