Kotlin sort hashmap in descending order
This worked for me.
val sortedMap = myHashMap.toSortedMap(reverseOrder())
Reference: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/reverse-order.html.
The reason you get the result in ascending order is because (from the values you presented) all dates have month=6 and year=2018.
If there are various dates then if you simply do compareByDescending
the result will be wrong.
Consider these dates:
21-05-2018, 22-4-2018.
If you sort descending you will get 1st 22-04-2018!
What you need to do is convert the dates in yyyy-MM-dd and then sort descending:
fun convertDate(d: String): String {
val array = d.split("-")
return array[2] + array[1] + array[0]
}
val sortedMap = myHashMap.toSortedMap(compareByDescending { convertDate(it) })
One more thing: your dates must have 2 digits for month and day and 4 digits for year, dates like 2-5-2018 will give wrong result.
Last edit: no need for -
in the concatenation.
You can use compareByDescending
:
val sortedMap = myHashMap.toSortedMap(compareByDescending { it })