Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Map in reverse order in Kotlin

Tags:

android

kotlin

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}
like image 374
Jéwôm' Avatar asked Mar 09 '18 15:03

Jéwôm'


1 Answers

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())
like image 142
zsmb13 Avatar answered Sep 28 '22 13:09

zsmb13