我是Scala的新手。
如果我有以下List
:
val ls = List("a", "a", "a", "b", "b", "c")
如何为列表中的每个元素创建一个包含多个外观的Map
?
例如,上面列表的Map
应为:
Map("a" -> 3, "b" -> 2, "c" -> 1)
答案 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))