Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 657
Willi Mentzel Avatar asked Jul 04 '17 10:07

Willi Mentzel


People also ask

How to group by in Kotlin?

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.

How do I create a list of strings in Kotlin?

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.


Video Answer


1 Answers

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>.

like image 64
Willi Mentzel Avatar answered Sep 19 '22 05:09

Willi Mentzel