Joel Joel - 3 months ago 17
Java Question

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

For the

Collectors.groupingBy()
that returns
Map<K,List<T>>
is it implied that the
List<T>
is in order that the stream is evaluated?

I see no explicit description of the ordering of the list, whereas the concurrent version explicitly states no ordering. If it weren't ordered somehow, I'd expect it to be a Collection though, and I don't see what other ordering it could possibly be, other than order received.

I'm hoping it's guaranteed that the last value in each list is the last value received for that group.

Answer

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.

Comments