如何在Kotlin中使用GROUP BY执行COUNT(*)?
假设我有一个下列类的对象列表。
class Contact( val name: String // ... )
我想检索一个映射名称到它的次数的映射Map
。
在一个基于SQL的数据库,我会查询:
SELECT name, count(*) FROM Contact;
在Kotlin中使用更高阶函数的最好方法是什么?
如果联系人的types为List
,则可以执行以下操作:
val numOccurencesMap = contacts.groupingBy { it.name }.eachCount()
numOccurencesMap
将是Map
。
val contacts = ArrayList() val occurences: Map occurences = contacts.groupingBy { it.name }.eachCount()