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

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

假设我有以下对象的列表 class。

class Contact(
    val name: String
    // ...
)

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

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

SELECT name, count(*) FROM Contact GROUP BY name;

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

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

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

numOccurencesMap 将是 Map<String, Int>.

类型