我有一个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()
}