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?
If you want to group elements and then apply an operation to all groups at one time, use the function groupingBy() . It returns an instance of the Grouping type. The Grouping instance lets you apply operations to all groups in a lazy manner: the groups are actually built right before the operation execution.
Inside main() , create a variable called numbers of type List<Int> because this will contain a read-only list of integers. Create a new List using the Kotlin standard library function listOf() , and pass in the elements of the list as arguments separated by commas.
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With