Search code examples
dictionarykotlinindexingkeytreemap

How to get the key of an index in a TreeMap


I want to get a key from it's index in a TreeMap. I can do this in Java Object firstKey = myMap.keySet().toArray()[index]; But how can I achieve the same in Kotlin?


Solution

  • You can achieve the same in Kotlin using map.keys.elementAt(index)

    import java.util.TreeMap
    
    fun main() {
       val index = 0
       val map = TreeMap<String, String>()
       map.put("1", "Test")
       map.put("2", "Test2")
       val obj = map.keys.elementAt(index)
       print(obj)
    }