Sort map by keys in Kotlin
This article explores different ways to sort a map in Kotlin according to the natural ordering of its keys.
1. Using TreeMap
A TreeMap is sorted according to the natural ordering of its keys. The idea is to pass your map to the TreeMap constructor to get a new tree map containing the same mappings but ordered according to its keys’ natural ordering.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.TreeMap fun main() { var map: MutableMap<String, String> = HashMap() map["UNITED STATES"] = "WASHINGTON, D.C." map["UNITED KINGDOM"] = "LONDON" map["ITALY"] = "ROME" map["SPAIN"] = "MADRID" val sortedMap: MutableMap<String, String> = TreeMap(map) println(sortedMap) } |
Output:
{ITALY=ROME, SPAIN=MADRID, UNITED KINGDOM=LONDON, UNITED STATES=WASHINGTON, D.C.}
2. Using LinkedHashMap
Alternatively, you can collect the sorted mappings in a LinkedHashMap, which remembers the iteration order of keys. This can be done with either sorted(), sortedBy() or sortedWith() function.
1. Using sorted() function
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun main() { val map: MutableMap<String, String> = HashMap() map["UNITED STATES"] = "WASHINGTON, D.C." map["UNITED KINGDOM"] = "LONDON" map["ITALY"] = "ROME" map["SPAIN"] = "MADRID" val sortedMap: MutableMap<String, String> = LinkedHashMap() map.keys.sorted().forEach { sortedMap[it] = map[it]!! } println(sortedMap) } |
Output:
{ITALY=ROME, SPAIN=MADRID, UNITED KINGDOM=LONDON, UNITED STATES=WASHINGTON, D.C.}
2. Using sortedBy() function
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun main() { val map: MutableMap<String, String> = HashMap() map["UNITED STATES"] = "WASHINGTON, D.C." map["UNITED KINGDOM"] = "LONDON" map["ITALY"] = "ROME" map["SPAIN"] = "MADRID" val sortedMap: MutableMap<String, String> = LinkedHashMap() map.entries.sortedBy { it.key }.forEach { sortedMap[it.key] = it.value } println(sortedMap) } |
Output:
{ITALY=ROME, SPAIN=MADRID, UNITED KINGDOM=LONDON, UNITED STATES=WASHINGTON, D.C.}
3. Using sortedWith() function
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun main() { val map: MutableMap<String, String> = HashMap() map["UNITED STATES"] = "WASHINGTON, D.C." map["UNITED KINGDOM"] = "LONDON" map["ITALY"] = "ROME" map["SPAIN"] = "MADRID" val sortedMap: MutableMap<String, String> = LinkedHashMap() map.entries .sortedWith(java.util.Map.Entry.comparingByKey()) .forEach { sortedMap[it.key] = it.value } println(sortedMap) } |
Output:
{ITALY=ROME, SPAIN=MADRID, UNITED KINGDOM=LONDON, UNITED STATES=WASHINGTON, D.C.}
That’s all about sorting map by keys in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)