Reputation: 3971
When I want to sort a Map
I use :
map.toSortedMap()
But how can I sort a map in the reverse order?
For example my Map<Double, Int>
is sorted with .toSortedMap()
, so I have :
{0.01=10, 0.05=7, 0.1=8, 0.25=6, 0.5=15, 1.0=3, 2.0=9, 5.0=8, 10.0=14, 20.0=6, 50.0=10}
I would like something like:
{50.0=10, 20.0=6, 10.0=14, 5.0=8, 2.0=9, 1.0=3, 0.5=15, 0.25=6, 0.1=8, 0.05=7, 0.01=10}
Upvotes: 16
Views: 7831
Reputation: 71
It is a bit late but hope this help.
for API <= 23
map.asIterable().reversed()
for API > 24
map.toSortedMap(Comparator.reverseOrder())
Upvotes: 4
Reputation: 9
Comparator.reverseOrder() works above the API level 21 ... the easiest way to get the keys from the sortedHashmap and reverse the keys list and then get values accordingly.
lateinit var entries: List<String>
entries = sortedList.keys.toList<String>()
entries = entries.reversed()
//get your values from map on the basis of keys
Upvotes: 0
Reputation: 89548
As @Venkata Raju said in the comment, you can use java.util.Comparator.reverseOrder()
for this (available since 1.8):
map.toSortedMap(Comparator.reverseOrder())
You can also use the reverseOrder()
function from the Kotlin standard library's kotlin.comparisons
package:
map.toSortedMap(reverseOrder())
Upvotes: 20