Reputation: 29864
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?
Upvotes: 35
Views: 14907
Reputation: 29864
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>
.
Upvotes: 69