Search code examples
kotlinhigher-order-functions

How to do a COUNT(*) with GROUP BY in Kotlin?


Let's say that I have a List of objects of the following class.

class Contact(
    val name: String
    // ...
)

I would like to retrieve a Map<String, Int> which maps a name to its number of occurences.

On a SQL-based database I would query:

SELECT name, count(*) FROM Contact GROUP BY name;

What is the best way to do this in Kotlin with higher order functions?


Solution

  • If contacts is of type List<Contact> you can do the following:

    val numOccurencesMap = contacts.groupingBy { it.name }.eachCount()
    

    numOccurencesMap will be of type Map<String, Int>.