使用Scala来实现workcount
//统计line集合中的数字个数,并取出字数前三
//line = List(List("hello tom hello jerry"),List("hello xiaobai hello"),List("hello tom"))
//预期效果:List((hello,5), (tom,2), (jerry,1))
package WordCount_
object Scala_WordCount {
def main(args: Array[String]): Unit = {
val line = List(List(" hello tom hello jerry"),List(" hello xiaobai hello "),List("hello tom "))
//1、先将line中的集合进行扁平化处理
//flatten可以将line中的每一个List元素取出
val list1: List[String] = line.flatten
//[end]:List( hello tom hello jerry, hello xiaobai hello , hello tom )
//2、将每个值切分出来
//因部分字符串前后有 空格,使用trim去除
//切分字符串结束后会存储为Array形式,此时还需要进行扁平化处理,使用flatMap
//flatMap能遍历list1,并进行扁平化处理。其中遍历同时可对list1元素进行操作
val list2: List[String] = list1.flatMap(_.trim.split(" "))
//[end]:List(hello, tom, hello, jerry, hello, xiaobai, hello, hello, tom)
//3、将切分出来的值拼接上数量
//map可以遍历并对list2进行操作,使用map将list2中的元素拼接称一个个对偶元组
val tuple1: List[(String, Int)] = list2.map((_,1))
//[end]:List((hello,1), (tom,1), (hello,1), (jerry,1), (hello,1), (xiaobai,1), (hello,1), (hello,1), (tom,1))
//4、统计每个单词出现的次数
//使用groupBy分组,groupBy带有遍历功能,以元组中的第一个元素分组,结果是map集合
//括号内的 _ :遍历list2时,每个list元素
//括号内的 _1:该元素中的第1个值
val map1: Map[String, List[(String, Int)]] = tuple1.groupBy(_._1)
//[end]:Map(tom -> List((tom,1), (tom,1)), xiaobai -> List((xiaobai,1)), jerry -> List((jerry,1)), hello -> List((hello,1), (hello,1), (hello,1), (hello,1), (hello,1)))
//keySet可以取出map集合中的键
val key1: Set[String] = map1.keySet
//[end]:Set(tom, xiaobai, jerry, hello)
//map中值为List集合,List的长度为所求
val value1: immutable.Iterable[Int] = map1.map(_._2.size)
//[end]:List(2, 1, 1, 5)
//5、将取出的keys1键与value1拼接
val set1: Set[(String, Int)] = key1.zip(value1)
//[end]:Set((tom,2), (xiaobai,1), (jerry,1), (hello,5))
//6、转为List,排序,反转
//set1的类型是Set,不能直接排序,故需要转为List
//sortBy排序只能升序排序,以set1的第二个元素进行排序
//reverse将排序结果反转,转变为降序排序
val list3: List[(String, Int)] = set1.toList.sortBy(_._2).reverse
//[end]:List((hello,5), (tom,2), (jerry,1), (xiaobai,1))
//7、取出字数出现的top3
//take取出几位元素
val list4: List[(String, Int)] = list3.take(3)
print(tuple3)
//[end]:List((hello,5), (tom,2), (jerry,1))
}
}