I'm looking for a neat way of converting a scala array to a map containing the frequency of the items occurring in the array.
For eg. :
Given an array like:
val arr = Array("one", "one", "two", "three", "one", "three")
I want a map:
Map("one" -> 3, "two" -> 1, "three" -> 2)
I can do this by writing a function such as
import scala.collection.mutable
def counter[T](arr: Array[T]) = {
val temp = mutable.Map[T, Int]()
for (i <- arr) {
if (temp.contains(i)) temp(i) += 1
else temp(i) = 1
}
temp
}
counter(arr)
I'd like to know if this can be done more efficiently.