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.

Download Code

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

Download Code

Output:

{ITALY=ROME, SPAIN=MADRID, UNITED KINGDOM=LONDON, UNITED STATES=WASHINGTON, D.C.}

2. Using sortedBy() function

Download Code

Output:

{ITALY=ROME, SPAIN=MADRID, UNITED KINGDOM=LONDON, UNITED STATES=WASHINGTON, D.C.}

3. Using sortedWith() function

Download Code

Output:

{ITALY=ROME, SPAIN=MADRID, UNITED KINGDOM=LONDON, UNITED STATES=WASHINGTON, D.C.}

That’s all about sorting map by keys in Kotlin.