2016-04-26 100 views

回答

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) 
} 
+0

你可以使用類型DataFrame(一列)的xs參數來寫它,而不使用collect()嗎?我在DataFrame上使用foreach並更新結果Map失敗。 –