Scala编写WordCound的方法比用Java编写简便的多
package com.auru.Leon
object WordCount {
def main(args: Array[String]): Unit = {
val array=Array[String]("a b c",
"b c",
"c"
)
val wordAndOneArray:Array[(String,Int)]=array.map(line => line.split(" ")).flatten.map(x => (x,1))
//flatten压成一组(二维数组压成一维数组) 将每一个元素计数
val wordCountArray:Map[String, Array[(String,Int)]]=wordAndOneArray.groupBy(X => X._1)
//将单词分组 scala.collection.immutable.Map[String,Array[(String, Int)]] =
// Map(b -> Array((b,1), (b,1)), 数组长度
// a -> Array((a,1)), 数组长度
// c -> Array((c,1), (c,1), (c,1))) 数组长度
val wordCount=wordCountArray.map(x => (x._1,x._2.length)).toList
println(wordCount)
}
//array.map(line => line.split(" ")).flatten.map(word => (word,1)).groupBy(wt => wt._1).map(x => (x._1,x._2.length))
}