如何在Kotlin中使用GROUP BY进行COUNT(*)?

Wil*_*zel 13 higher-order-functions kotlin

假设我有以下类的对象列表.

class Contact(
    val name: String
    // ...
)
Run Code Online (Sandbox Code Playgroud)

我想检索一个Map<String, Int>将名称映射到其出现次数的名称.

在基于SQL的数据库上,我会查询:

SELECT name, count(*) FROM Contact;
Run Code Online (Sandbox Code Playgroud)

在具有更高阶函数的Kotlin中执行此操作的最佳方法是什么?

Wil*_*zel 29

如果联系人属于类型,List<Contact>您可以执行以下操作:

val numOccurencesMap = contacts.groupingBy { it.name }.eachCount()
Run Code Online (Sandbox Code Playgroud)

numOccurencesMap将是类型Map<String, Int>.