为每个List元素创建一个包含#of外观的Map

时间:2013-09-13 19:46:32

标签: scala collections

我是Scala的新手。

如果我有以下List

val ls = List("a", "a", "a", "b", "b", "c")

如何为列表中的每个元素创建一个包含多个外观的Map

例如,上面列表的Map应为:

Map("a" -> 3, "b" -> 2, "c" -> 1)

3 个答案:

答案 0 :(得分:5)

list.foldLeft(Map[String, Int]() withDefaultValue 0) { (m, x) => m + (x -> (m(x) + 1)) }

代码片段:

scala> val list = List("a", "a", "b", "c", "c", "a")
list: List[String] = List(a, a, b, c, c, a)

scala> list.foldLeft(Map[String, Int]() withDefaultValue 0) { (m, x) => m + (x -> (1 + m(x))) }
res1: scala.collection.immutable.Map[String,Int] = Map(a -> 3, b -> 1, c -> 2)

(直接基于Count occurrences of each element in a List[List[T]] in Scala

答案 1 :(得分:2)

效率不如Erik的foldLeft解决方案:

val ls = List("a", "a", "a", "b", "b", "c")
ls.groupBy(identity).mapValues(_.size)
res0: scala.collection.immutable.Map[String,Int] = Map(a -> 3, c -> 1, b -> 2)

答案 2 :(得分:2)

使用scalaz

xs foldMap (x => Map(x -> 1))