简单的wordcount

 1 object Test16_CommonWordCount {
 2   def main(args: Array[String]): Unit = {
 3     val list = List(
 4       "hello",
 5       "hello world",
 6       "hello scala",
 7       "hello world",
 8       "hello scala",
 9       "hello java"
10     )
11     //1、对字符串进行切分,得到一个打散所有单词的列表
12     val wordlist = list.flatMap(_.split(","))
13     println(wordlist)
14 
15     //2、相同的单词进行分组
16     val grouplist = wordlist.groupBy( word => word )
17     println(grouplist)
18 
19     //3、对分组之后的list取长度,得到每个单词的个数
20     val countMap = grouplist.map(kv => (kv._1, kv._2.length))
21 
22     //4、将map转换为list,排序取出前3
23     val sortlist = countMap.toList
24       .sortWith( _._2 > _._2 )
25       .take(3).foreach(println)
26   }
27 }

 

posted @ 2022-05-23 16:06  小王同学学编程  阅读(28)  评论(0编辑  收藏  举报
levels of contents