计算没有.groupBy的元素的出现次数

时间:2014-11-22 20:23:00

标签: list scala scala-collections

我需要计算列表中元素的出现次数。

列表如下所示:List[(String, String, Int)] - (String, String, Int)元组列表。

示例:

List(("Gregor", "Math", 6), ("Mark", "Math", 33), 
     ("Gregor", "IT", 44),  ("Jane", "Math", 3), 
     ("Mark", "Geography", 44), ("Gregor", "sdf", 32))

我需要返回对列表(名称,列表中的出现次数) 对于这个例子,它应该是

List(("Gregor", 3), ("Mark", 2), ("Jane", 1))

我尝试使用map和foldLeft,但我不知道我该怎么做

3 个答案:

答案 0 :(得分:3)

您只需使用foldLeft

即可完成此操作
val t = List(("Gregor", "Math", 6), ("Mark", "Mat", 33), 
    ("Gregor", "IT", 44), ("Jane", "Math", 3), ("Mark", "Geography", 44), 
    ("Gregor", "sdf", 32))

val res = t.foldLeft(Map[String, Int]()) { case(m, (n, _, _)) => 
    m + (n -> (m.getOrElse(n, 0) + 1)) 
}.toList

答案 1 :(得分:0)

users.groupBy(u => u._1).map(u => (u._1, u._2.length)).toList

答案 2 :(得分:0)

scala> val list = List(("Gregor", "Math", 6), ("Mark", "Mat", 33), ("Gregor", "IT", 44), ("Jane", "Math", 3), ("Mark", "Geography", 44), ("Gregor", "sdf", 32))
list: List[(String, String, Int)] = List((Gregor,Math,6), (Mark,Mat,33), (Gregor,IT,44), (Jane,Math,3), (Mark,Geography,44), (Gregor,sdf,32))

scala> val res = list.groupBy(_._1) map { case (k, xs) => k -> xs.size } toList
res: List[(String, Int)] = List((Gregor,3), (Jane,1), (Mark,2))