For Kotlin's ordered collections, does groupBy maintain a stable ordering in the resulting groups?
For example will:
listOf(1, 2, 2, 3,)
.withIndex() // [(0, 1), (1, 2), (2, 2), (3, 3)]
.groupBy {it.value } // { 1: [(0, 1)], 2: [(1, 2), (2, 2), (6, 2)]...}
.mapValues { it.map { it.index } } // { 1: [0], 2: [1, 2, 6], 3: [3]}
.get(2)
always be [1, 2, 6], or is the ordering of the list undefined?
From the documentation, it is not specified what the order of the values will be, but the order of the keys are preserved:
The returned map preserves the entry iteration order of the keys produced from the original collection.
That said, you can look at the implementation and see that, at least for now, the order is stable. It's just looping over the collection and add
ing each element to the List
corresponding to the key.