Search code examples
kotlinhashmap

Kotlin sort hashmap in descending order


I have val myHashMap = HashMap<String, MutableList<TestItem>>(), hashmap key value is formatted date as a string for example 20-06-2018 how can I sort this hashMap in descending order?

expected result:

22-06-2018 : []
21-06-2018 : []
20-06-2018 : []

I use this code to sort it, but result is in ascending order:

val sortedMap = myHashMap.toSortedMap(compareBy { it })

Solution

  • You can use compareByDescending:

    val sortedMap = myHashMap.toSortedMap(compareByDescending { it })