DEV Community

loizenai
loizenai

Posted on

Kotlin convert Map to SortedMap

https://grokonez.com/kotlin/kotlin-convert-map-sortedmap

Kotlin convert Map to SortedMap

In the tutorial, JavaSampleApproach will show you how to convert Kotlin Map to SortedMap.

I. Convert Kotlin Map to SortedMap

1. using toSortedMap()

Method signature:

public fun <K : Comparable<K>, V> Map<out K, V>.toSortedMap(): SortedMap<K, V> = TreeMap(this)

-> Converts a Map to a SortedMap so iteration order will be in key order.

Practice:


val simpleMap = mapOf(Pair(4, "four"), Pair(8, "eight"), Pair(5, "five"), Pair(7, "seven"), Pair(10, "ten"), Pair(1, "one"))
println(simpleMap)
/*
    {4=four, 8=eight, 5=five, 7=seven, 10=ten, 1=one}
*/

val sortedMap = simpleMap.toSortedMap();
println(sortedMap)
/*
    {1=one, 4=four, 5=five, 7=seven, 8=eight, 10=ten}
*/

2. using toSortedMap() with Comparator

Method signature:

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

-> Converts a Map to a SortedMap with comparator so that iteration order will be in the order defined by the comparator.

Practice:

More at:

https://grokonez.com/kotlin/kotlin-convert-map-sortedmap

Kotlin convert Map to SortedMap

Top comments (0)