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 ?
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 provides similar functionality when running on the JVM. Map
has a toSortedMap
function which returns a sorted version of itself. The implementation actually uses a TreeMap under the hood. This function is missing on other Kotlin platforms, possibly because there was no corresponding TreeMap implementation available on them.
See the documentation here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/to-sorted-map.html