Consider a list List<People>
where the elements are sorted in ascending order of People.getAge()
. If we group this list using Collectors.groupingBy(People::getCity)
, would the resultant lists for each of the groups/cities remain sorted on age?
In practice, it does seem to preserve the order. I'm looking for a guarantee.
The Javadoc for the method says:
If preservation of the order in which elements appear in the resulting Map collector is not required, using groupingByConcurrent(Function) may offer better parallel performance
I'm not sure if this refers to the order of items on list.
Does Groupby preserve order? Groupby preserves the order of rows within each group.
If you have an ordered stream and perform operations which guarantee to maintain the order, it doesn't matter whether the stream is processed in parallel or sequential; the implementation will maintain the order.
Collectors is a final class that extends Object class. It provides reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc. It returns a Collector that produces the arithmetic mean of a double-valued function applied to the input elements.
In Java 8, you retrieve the stream from the list and use a Collector to group them in one line of code. It's as simple as passing the grouping condition to the collector and it is complete. By simply modifying the grouping condition, you can create multiple groups.
The key to understanding the contract is where it says "the order in which elements appear". It talks about whether they arrive in order, which implies whether they are passed in to the key extractor Function
and to any downstream collector in order; it doesn't say anything about whether the order will be preserved in any resulting accumulation; in fact the current implementation of groupingBy
uses a HashMap
which does not preserve the key order.
You ask if it refers to the order of items on the list. If you are referring to the List that the Stream was created from, a Stream created on a List does start out ordered, but some stream operations change the order or make it unordered, so the ordering it refers to refers to the resulting order after pipeline operations are done IF the stream remains ordered. If stream operations make the stream unordered, the order in which elements appears at the collector is not an issue any longer.
If you are referring to the order of items in the List the grouped items are collected to, yes, it does, because the "order in which the elements appear" is the order in which the elements are processed. The same holds true when grouping to a downstream collector; if the Stream is still ordered, and you group to a downstream collector that preserves order, this will preserve that order, while the Concurrent version may not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With