How to do 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 get Map<String, Int>

one that maps the name to the number of its occurrences.

In a SQL database, I would query:

SELECT name, count(*) FROM Contact;

      

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

+3


source to share


2 answers


If the contacts are of type List<Contact>

, you can do the following:

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

      



numOccurencesMap

will be of type Map<String, Int>

.

+11


source


        val contacts = ArrayList<Contact>()
        val occurences: Map<String, Int>
        occurences = contacts.groupingBy { it.name }.eachCount()

      



+1


source







All Articles