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.

Download Code

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.

Download Code

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.