如何获取 TreeMap 中索引的键

How to get the key of an index in a TreeMap

我想从它在 TreeMap 中的索引中获取一个键。我可以在 Java Object firstKey = myMap.keySet().toArray()[index]; 中做到这一点 但是我怎样才能在 Kotlin 中实现同样的目标呢?

您可以使用 map.keys.elementAt(index)

在 Kotlin 中实现相同的目的
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)
}

如果你因为某些原因需要坚持toArray()[index]调用,你可以使用myMap.keys.toTypedArray()[index],看下面的例子:

import java.util.TreeMap

fun main() {
    val map = TreeMap<String, String>()
    map.put("key", "value")
    println(map.keys.toTypedArray()[0])
}

否则,@Marek 使用 myMap.keys.elementAt(index) 的方法非常好。