这里给出两种方式,供初学者参考。
方式一:
val lines = List("show me the money", "show me the meaning of being lonely", "triple kill", "mega kill","monster kill","holy shit")
val map = lines.flatMap { line => line.split(" ") }.foldLeft(Map.empty[String, Int]){(count, word) => count + (word -> (count.getOrElse(word, 0) + 1))}
方式二:
lines.flatMap { line => line.split(" ") }.map { x => (x,1) }.groupBy(_._1).mapValues(f=>f.size).foreach(println)