Home > Enterprise >  Kotlin - lack of TreeMap
Kotlin - lack of TreeMap

Time:11-05

Why there are no TreeMap in Kotlin ? I know we can use the TreeMap using java utils, but this is probably not the real reason. Do we can achieve the same using HashMap ?

CodePudding user response:

A TreeMap is different from a HashMap because it has a specific order when iterating through the elements. The items in it will be sorted according to their natural ordering or according to whatever comparator it was built with. If you iterate over a HashMap the order of the elements will be essentially random. In Java TreeMap is a specific type of SortedMap.

Kotlin Maps have a toSortedMap function which gives you a sorted version of the map. This should behave like a TreeMap although I don't know if it's implemented the same way. See the documentation here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/to-sorted-map.html

  • Related