s1m0nw1
s1m0nw1

Reputation: 82087

In Kotlin, how can I iterate a TreeMap in reversed order?

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

Answers (2)

xihadulislam
xihadulislam

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

zsmb13
zsmb13

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:

  • the K type parameter doesn't have to be Comparable, which was previously required by the reverseOrder call
  • descendingMap returns a view of the original Map instead of copying it
  • the function is marked inline like most similar ones from the standard library

Upvotes: 2

Related Questions