scala 实现wordCount

object ScalaWordCount {

  def main(args: Array[String]): Unit = {
    val lines = List("hello world hello java hello scala","hello world hello java hello scala","hello java hello scala")
    //获取单词
    val words = lines.flatMap(_.split(" "))
    //用元组来存储
    val tuples = words.map((_,1))
    //通过key分组
    val grouped = tuples.groupBy(_._1)

    //计算单词数量
    val result = grouped.mapValues(_.size)
    //排序
    val sorted = result.toList.sorted.reverse
    println(sorted)
  }



}

很明显代码量比Java少特别多

你可能感兴趣的:(Scala)