-2

What does the method "toSortedMap"? According to the documentation we can read:

Converts this Map to a SortedMap. The resulting SortedMap determines the equality and order of keys according to their natural sorting order.

But what does natural sorting order mean ? Their example doesn't look sorted.

discCard
  • 421
  • 1
  • 5
  • 16

1 Answers1

1

The function signature of toSortedMap is defined as:

fun <K : Comparable<K>, V> Map<out K, V>.toSortedMap(): SortedMap<K, V>

The sort order thus is defined by the comparison logic defined while implementing Comparable by the type K resembling the keys.

For numeric and string values, this is most likely the intuitive ascending sort order. For custom types, e.g. User, a custom implementation to fulfill the Comparable interface must be provided.

Alternatively there is a second signature, which allows to provide a custom Comparator<in K> to make use of a custom sort order, if the keys of type K don't implement Comparable<K> or this implementation does not fullfil the expected ordering.

fun <K, V> Map<out K, V>.toSortedMap(
    comparator: Comparator<in K>
): SortedMap<K, V>

Additional information can be found in the documentation of SortedMap and Comparable<T>.

Endzeit
  • 4,810
  • 5
  • 29
  • 52