Jen
Jen

Reputation: 1338

Does Kotlin's sortedBy keeps order of equal values?

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

Upvotes: 2

Views: 578

Answers (1)

Jen
Jen

Reputation: 1338

Yes, per the official docs:

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

Upvotes: 5

Related Questions