linus muema
02/05/2021, 10:31 AM[Elijah=51, Chloe=144, Natalie=207, Jayden=390, Elizabeth=485, Matthew=485]
In this map, I would like values to be sorted in a descending order first. Then sort the keys in an alphabetical order.
i.e Elizabeth
must appear before Matthew
even though their values are the same.
🤷♂️Niklas Gürtler
02/05/2021, 10:42 AMMarc Knaup
02/05/2021, 10:43 AMval map = mapOf(
"Elijah" to 51, "Chloe" to 144, "Natalie" to 207, "Jayden" to 390, "Matthew" to 485, "Elizabeth" to 485,
)
val sortedMap = map
.toList()
.sortedWith(compareBy<Pair<String,Int>> { it.second }.thenBy { it.first })
.toMap()
linus muema
02/05/2021, 10:49 AM{Elijah=51, Chloe=144, Natalie=207, Jayden=390, Elizabeth=485, Matthew=485}
Niklas Gürtler
02/05/2021, 10:52 AMtoMap
does not return a HashMap
which does not have its fast amortized O(1) look up time)Marc Knaup
02/05/2021, 10:52 AMval map = mapOf(
"Elijah" to 51, "Chloe" to 144, "Natalie" to 207, "Jayden" to 390, "Matthew" to 485, "Elizabeth" to 485,
)
val sortedMap = map
.toList()
.sortedWith(compareByDescending<Pair<String,Int>> { it.second }.thenBy { it.first })
.toMap()
Marc Knaup
02/05/2021, 10:54 AMtoMap()
uses LinkedHashMap
which should also have O(1) lookup. It just uses more memory to maintain order.linus muema
02/05/2021, 10:54 AMNiklas Gürtler
02/05/2021, 10:55 AMIvan Pavlov
02/05/2021, 10:57 AMentries
instead of intermediate toList
?Marc Knaup
02/05/2021, 10:59 AMtoMap()
at the end which operates on Iterable<Pair<…>>
Ivan Pavlov
02/05/2021, 11:00 AMMarc Knaup
02/05/2021, 11:00 AMval sortedMap = map
.entries
.sortedWith(compareByDescending<Map.Entry<String, Int>> { it.key }.thenBy { it.value })
.associate { it.key to it.value }
Ivan Pavlov
02/05/2021, 11:27 AMMarc Knaup
02/05/2021, 11:28 AMassociateBy
only allows you to specify the key, not the value.Ivan Pavlov
02/05/2021, 11:34 AMMarc Knaup
02/05/2021, 11:35 AM