在Scala数组中查找每个不同元素的计数的最有效实现是什么?
答案 0 :(得分:3)
val xs = Array("a", "b", "c", "c", "a", "b", "c", "b", "b", "a")
xs.groupBy(identity).mapValues(_.length)
或者像这样:
xs.foldLeft(Map[String, Int]().withDefaultValue(0))((acc, x) => acc + (x -> (acc(x) + 1)))
如果您想提高效率,可以使用内部可变性来防止复制:
def countElems[A](xs: Array[A]): Map[A, Int] = {
val result = collection.mutable.Map[A, Int]().withDefaultValue(0)
xs foreach { x => result += (x -> (result(x) + 1)) }
result.toMap // this copies and makes it immutable, O(number of distinct elements)
}