Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Grouping and ordering the top 3 values in a list

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading