object WordCount {
def main(args: Array[String]): Unit = {
val list=List("hello scala java","hello mysql scala","hello oracel","hello javaee")
//读出每一个单词 List(hello, scala, java, hello, mysql, scala, hello, oracel, hello, javaee)
val words: List[String] = list.flatMap(_.split(" "))
//每一个元素变成List((hello,1), (scala,1), (java,1), (hello,1), (mysql,1), (scala,1), (hello,1), (oracel,1), (hello,1), (javaee,1))
val wordOne: List[(String, Int)] = words.map((_,1))
//根据元素分类 五个键值对
// HashMap(javaee -> List((javaee,1)), java -> List((java,1)), oracel -> List((oracel,1)), scala -> List((scala,1), (scala,1)), mysql -> List((mysql,1)), hello -> List((hello,1), (hello,1), (hello,1), (hello,1)))
val groupWords: Map[String, List[(String, Int)]] = wordOne.groupBy(_._1)
// f代表键值对 java -> List((java,1))
val result=groupWords.map(f=>{
//f._2 List((java,1))
val list:List[(String,Int)]=f._2
val nums:List[Int]=list.map(_._2)
//求和
val counts=nums.sum
//每个f返回结果的形式 hello -> 4
(f._1,counts)
})
println(result)
}
}
使用IDEA scala实现wordcount
最新推荐文章于 2024-03-11 16:24:10 发布