函数原型:
def foldLeft[B](z: B)(op: (B, A) => B): B = {
var result = z
this.seq foreach (x => result = op(result, x))
result
}
实现代码:
val lines = Source.fromFile("E://test.txt").getLines()
val seqop = (result: mutable.HashMap[String, Int], line: String) => {
val wordcount = line.replace(",", " ").replace(".", " ").replace("(", " ").replace(")", " ").split(" ").filter(_.trim.length > 0).map(word => (word, 1))
wordcount.foreach(wc => {
val addOne = (wc._1, result.getOrElse(wc._1, 0) + wc._2)
result += addOne
})
result
}
val combop = (result1: mutable.HashMap[String, Int], result2: mutable.HashMap[String, Int]) => {
result1 ++= result2
}
val test = lines.foldLeft(new mutable.HashMap[String, Int]())(seqop)
println(test)
文件内容:
one one two
one two three
four two three
运行结果:
Map(one -> 3, three -> 2, four -> 1, two -> 3)