使用foldLeft函数,实现简易的wordCount
import scala.collection.mutable object Demo_019 { def main(args: Array[String]): Unit = { val list = List("bigdata han hello ", "bigdata han aaa aaa aaa ccc ddd uuu") val map01 = mutable.Map[String, Int]() list.foldLeft(map01)(count2) println(map01) } def count2(map2: mutable.Map[String, Int], str: String): mutable.Map[String, Int] = { val arr: Array[String] = str.split(" ") for (elem <- arr) { map2 += (elem -> (map2.getOrElse(elem, 0) + 1)) } map2 }
运行结果为: