Reputation: 82087
I have a TreeMap
and want to iterate it in reversed order. What would be an idiomatic way to do this?
val tree = TreeMap(mapOf(1 to "one", 2 to "two", 3 to "three"))
tree.forEach { println(it.key) }
Expected Output would be 3, 2, 1
NOTE: this is a self-answered question: https://stackoverflow.com/help/self-answer
Upvotes: 1
Views: 1035
Reputation: 1
You use reversed() method for this. Here is an Example :
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()
}
Or you can declare it when it initializes
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()
}
Upvotes: 0
Reputation: 89668
I'd go with this implementation of forEachReversed
:
inline fun <K, V> TreeMap<K, V>.forEachReversed(action: (Map.Entry<K, V>) -> Unit) {
descendingMap().forEach(action)
}
The differences from your solution are the following:
K
type parameter doesn't have to be Comparable
, which was previously required by the reverseOrder
calldescendingMap
returns a view of the original Map
instead of copying itinline
like most similar ones from the standard libraryUpvotes: 2