scala版本的wordCount

object word_count {

  def main(args: Array[String]) {
    /*
    scalawordCount
     */
    val arr = Array(2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2)
    val map = wordCount(arr)
    for ((k, v) <- map) {
      println(k + "\t" + v)
    }
  }

  def wordCount(arr: Array[Int]): Map[Int, Int] = {
    // map()對每個元素計數形成(_,1),groupBy()對元組中的對一個分組形成key-value形式,然後求每個value的長度
    arr.map((_, 1)).groupBy(_._1).mapValues(_.length)
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章