在 Kotlin 中,如何以相反的顺序迭代树状图?



我有一个TreeMap,想以相反的顺序迭代它。这样做的惯用方法是什么?

val tree = TreeMap(mapOf(1 to "one", 2 to "two", 3 to "three"))
tree.forEach { println(it.key) }

预期产出将是3, 2, 1

注意:这是一个自我回答的问题:https://stackoverflow.com/help/self-answer

我会使用这个forEachReversed实现:

inline fun <K, V> TreeMap<K, V>.forEachReversed(action: (Map.Entry<K, V>) -> Unit) {
descendingMap().forEach(action)
}

与您的解决方案的区别如下:

  • K类型参数不必Comparable,这是以前reverseOrder调用所必需的
  • descendingMap返回原始Map的视图,而不是复制它
  • 该函数被标记为inline与标准库中大多数类似的函数一样

为此使用 reversed(( 方法。下面是一个例子:

fun sortPeople(names: Array<String>, heights: IntArray): Array<String> {
val treeMap: TreeMap<Int, String> = TreeMap()
names.forEachIndexed { index, s -> treeMap[heights[index]] = s }
return treeMap.values.reversed().toTypedArray()
}

或者你可以在它初始化时声明它

fun sortPeople(names: Array<String>, heights: IntArray): Array<String> {
val treeMap: TreeMap<Int, String> = TreeMap(Collections.reverseOrder())
names.forEachIndexed { index, s -> treeMap[heights[index]] = s }
return treeMap.values.toTypedArray()
}

最新更新