Java Collectors.groupingBy()---is List ordered?

I did a real test, I init a ArrayList<TimeBased> with this order:

{"1", "2019-03-22 10:20:03", "1"},
{"2", "2019-03-22 10:30:03", "2"},
{"2", "2019-03-22 11:20:03", "3"},
{"1", "2019-03-22 11:20:15", "4"},
{"3", "2019-03-22 11:35:03", "5"},
{"2", "2019-03-22 12:20:03", "6"}

and groupingBy first and second column, but the result was:

id  birth                        number
1   Fri Mar 22 10:20:03 CST 2019 1
1   Fri Mar 22 11:20:15 CST 2019 4
2   Fri Mar 22 12:20:03 CST 2019 6
2   Fri Mar 22 11:20:03 CST 2019 3
2   Fri Mar 22 10:30:03 CST 2019 2
3   Fri Mar 22 11:35:03 CST 2019 5

so you see, the order is unexpected(date column order confused).

and after i do this(add LinkedList::new):

Map<Integer, Map<Date, List<TimeBased>>> grouped =
                timeBasedBeans.stream().collect(groupingBy(TimeBased::getId, groupingBy(TimeBased::getPeriod,
                        LinkedHashMap::new, toList())));

then the order is right:

id  birth                        number
1   Fri Mar 22 10:20:03 CST 2019 1
1   Fri Mar 22 11:20:15 CST 2019 4
2   Fri Mar 22 10:30:03 CST 2019 2
2   Fri Mar 22 11:20:03 CST 2019 3
2   Fri Mar 22 12:20:03 CST 2019 6
3   Fri Mar 22 11:35:03 CST 2019 5

The documentation for groupingBy() says:

Implementation Requirements:

This produces a result similar to:

groupingBy(classifier, toList());

The documentation for toList() says:

Returns:

a Collector which collects all the input elements into a List, in encounter order

So, to answer your question, as long as your stream has a defined encounter order, you're guaranteed to get ordered lists.


EDIT: As @Holger points out, groupingBy() would also have to respect encounter order to preserve toList()'s ordering constraint. The fact that it does is strongly implied in this note:

Implementation Note:

...If preservation of the order in which elements are presented to the downstream collector is not required, using groupingByConcurrent(Function, Collector) may offer better parallel performance.


Unfortunately, this guarantee is not stated clearly.

However, the resulting Collector currently does not have the UNORDERED characteristic, so in fact, the resulting List is ordered.

The remaining question is, because there is no API contract disallowing it, could a future version (or an alternative implementation) add that characteristic and produce unordered lists? In practice, both OpenJDK and Oracle have been extremely unwilling to introduce such breaking changes even when there is strong justification for it.

Here, there is little justification to make such a change; I think it's safe to rely on this behavior.