scala WordCount

WordCount

package scala

import scala.io.Source

object Demo22WordCount {
  def main(args: Array[String]): Unit = {

    //1、读取文件
    //转换成集合
    val lines: List[String] = Source.fromFile("data/words.txt").getLines().toList

    //将每一行单词拆分出来,一行转换成多行
    val words: List[String] = lines.flatMap((line :String ) => line.split(","))

   //3、按照单词进行分组
    //key 是单词 value 是单词的集合
    val group: Map[String, List[String]] = words.groupBy((word:String ) => word)

    //4、统计单词的数量,统计集合的长度
    val count: Map[String, Int] =group.map((kv:(String ,List[String] ))=>{
      //当前集合
      val word: String = kv._1
      //集合的长度
      val ws: List[String] = kv._2
      //单词的数量
      val num: Int = ws.length

      (word,num)
    })

    count.foreach(println)

    //简写
    Source
      .fromFile("data/words.txt")
      .getLines() //获取所有行
      .toList //转换成集合
      .flatMap(_.split(",")) //将每一行的单词拆分出来
      .groupBy(w => w) //按照单词分组
      .mapValues(_.length) //统计单词的数量
      .foreach(println)


  }
}

 

posted @ 2021-07-14 11:24  坤坤无敌  阅读(107)  评论(0)    收藏  举报