I have a list similar in concept to the following:
val selectedValues = listOf("Apple", "Apple", "Apple", "Grape", "Grape", "Cherry")
I need a way to group and sort it so that I get something like this:
Apple: 3
Grape: 2
Cherry: 1
I got a little bit of headway with this answer but I want it to be ordered by the count (most to least) and I can’t seem to figure out how to get there.
I feel like the answer I posted gets me very close to what I want but I just need to figure out how to get it to work the way I need to and I’m just hitting a wall and need a little assistance as I’m still fairly new to Kotlin.
>Solution :
You could try something like this:
fun main(args : Array<String>) {
val selectedValues = listOf("Apple", "Apple", "Apple", "Grape", "Grape", "Cherry")
val solution = selectedValues
.groupBy { it }
.mapValues { it.value.size }
.toList()
.sortedByDescending { (_, value) -> value }
.toMap()
println(solution)
}
This will returns you
{Apple=3, Grape=2, Cherry=1}
which I think is (more or less) what you were after.