Scala实现单词统计

138 阅读1分钟
object count {
  val stringList = List("Hello Scala Hbase kafka""Hello Scala Hbase""Hello Scala""Hello")
  val wordList: List[String] = stringList.flatMap(str => str.split(" "))
  val wordToWordsMap: Map[String, List[String]] = wordList.groupBy(word => word)
  val wordToCountMap: Map[String, Int] = wordToWordsMap.map(tuple => (tuple._1, tuple._2.size))
  val sortList: List[(String, Int)] = wordToCountMap.toList.sortWith {
    (left, right) => {
      left._2 > right._2
 } 
} 
 def main(args: Array[String]): Unit = { 
    val resultList: List[(String, Int)] = sortList.take(3)
    println(resultList) 
  } 
}