2017-07-04 95 views
2

假设我有一个下列类的对象列表。如何在Kotlin中使用GROUP BY计算COUNT(*)?

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

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

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

SELECT name, count(*) FROM Contact; 

什么是高阶函数为此在科特林的最佳方式?

回答

10

如果接触的类型是List<Contact>你可以做以下的:

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

numOccurencesMapMap<String, Int>类型。

2
 val contacts = ArrayList<Contact>() 
     val occurences: Map<String, Int> 
     occurences = contacts.groupingBy { it.name }.eachCount() 
+1

这是我的方法的确切副本,不是吗? :( –