package com.huc.WordCount
object WordCount1 {
def main(args: Array[String]): Unit = {
// 需求:将集合中出现的相同的单词,进行计数,取计数排名前三的结果
val stringList = List("Hello Scala Hbase kafka", "Hello Scala Hbase", "Hello Scala", "Hello")
// 步骤一:扁平化拆分成长字符串
val strings = stringList.flatMap((s: String) => s.split(" "))
val strings1 = stringList.flatMap(_.split(" "))
println(strings)
// 步骤二:将相同的单词分组到一起
strings.groupBy((s: String) => s)
val map = strings.groupBy(s => s)
println(map)
// 步骤三:转换数据格式为 (单词,次数)
val map1 = map.map((tuple: (String, List[String])) => (tuple._1, tuple._2.size))
val map2 = map.map(tuple => (tuple._1, tuple._2.size))
println(map1)
val map3 = map.mapValues(_.size)
println(map3)
// 步骤四:排序
val tuples = map3.toList.sortBy((tuple: (String, Int)) => tuple._2)
println(tuples)
val tuples1 = map3.toList.sortBy((test: (String, Int)) => test._2)(Ordering[Int].reverse)
val tuples2 = map3.toList.sortBy(_._2)(Ordering[Int].reverse)
println(tuples1)
val tuples3 = map3.toList.sortWith((left: (String, Int), right: (String, Int)) => left._2 > right._2)
val tuples4 = map3.toList.sortWith(_._2 > _._2)
println(tuples3)
// 步骤五:取top3
println(tuples4.take(3))
// 熟练的写法
val tuples5 = stringList.flatMap(_.split(" "))
.groupBy(s => s)
.map(tuple => (tuple._1, tuple._2.size))
.toList.sortWith(_._2 > _._2)
.take(3)
println(tuples5)
}
}
Scala WordCount案例1(将集合中出现的相同的单词,进行计数,取计数排名前三的结果)
最新推荐文章于 2024-06-06 19:08:35 发布