Does Kotlin's sortedBy keeps order of equal values?

Viewed 175

Suppose I have a list of values defined with some arbitrary order.

val list = listOf("a", "aa", "b", "bb")

If I sort this list using sortedBy using some Comparable property of the values.

val sorted = list.sortedBy { it.length }

Will the original arbitrary order be preserved for values that compare as equal?

["a", "b", "aa", "bb"] // good
["b", "a", "aa", "bb"] // bad
["a", "b", "bb", "aa"] // bad
["b", "a", "bb", "aa"] // bad
1 Answers

Yes, per the official docs:

The sort is stable. It means that equal elements preserve their order relative to each other after sorting.

Related