Traverse a Map in sorted order in Kotlin
This article explores different ways to traverse a Map in sorted order in Kotlin.
The Map in Kotlin offers great performance but doesn’t maintain sorted order of its keys. To convert a Map to a SortedMap, you can use the toSortedMap() function. It results in a SortedMap that determines the equality and order of keys according to their natural sorting order. If you need reverse ordering of keys, you can pass the reverseOrder() comparator to the map.toSortedMap() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import kotlin.random.Random private const val chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun getRandomKey(len: Int): String { val sb = StringBuilder() for (i in 0 until len) { val rIndex = Random.nextInt(chars.length) sb.append(chars[rIndex]) } return sb.toString() } fun main() { val map: MutableMap<String, Int> = mutableMapOf() for (i in 1..15) { map[getRandomKey(6)] = i } print(map.toSortedMap()) } |
Output (will vary):
{JGbJPr=3, OAmcrF=13, OkfQCe=15, RJehBx=10, Sfdmxf=1, TuvBXy=9, VmgbDF=11, hKUyvu=8, hTMKim=5, ieFgDu=14, keOMwr=7, qfzXaa=4, tTwhZf=12, vrcsOM=6, wRGzAf=2}
To get the sorted-order iteration, consider using a java.util.TreeMap, which is implemented as a Red-black tree and by default, it has keys sorted according to their natural ordering.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.TreeMap import kotlin.random.Random private const val chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun getRandomKey(len: Int): String { val sb = StringBuilder() (0 until len).forEach { _ -> val rIndex = Random.nextInt(chars.length) sb.append(chars[rIndex]) } return sb.toString() } fun main() { val map: MutableMap<String, Int> = TreeMap() for (i in 1..15) { map[getRandomKey(6)] = i } for (entry in map.entries) { println(entry) } } |
Output (will vary):
Gxihmf=4
HjGHlb=9
JUiZTg=13
Jifngb=7
JrQWcR=10
LsRJLs=11
NWcIxh=2
RwuuLS=8
WnbYuO=3
aYNceA=1
asYCfn=14
bAJnlg=12
nMpwgz=15
uFNfeo=5
ygntLs=6
That’s all about traversing a map in sorted order 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 :)