大数据全系列 教程
1869个小节阅读:464.8k
目录
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
使用模式匹配升级WordCount案例。
拷贝chapter07.WordCount ->chapter08.WordCountMatch
xxxxxxxxxx
package com.itbaizhan.chapter08
import scala.io.{BufferedSource, Source}
//单词统计:通过学过的集合的方法,统计指定文件input/wc.txt中每个单词出现的总次数
object WordCountMatch {
def main(args: Array[String]): Unit = {
//......
//TODO 9.从word2OneList集合中过滤调用元素的值为空格的垃圾数据
var word2OneList: List[(String, Int)] = words.map((_, 1))
/*word2OneList = word2OneList.filter(//保留的返回true,想被过滤掉返回false即可
eleTup=>{//(hello,1) 或 ( ,1)
if(eleTup._1!=null && !eleTup._1.trim.isEmpty){
true //保留
}else{
false//过滤掉
}
})*/
word2OneList = word2OneList.filter {
case (key,_) =>{
if(key!=null && !key.trim.isEmpty){
true
}else{
false
}
}
}
//println(word2OneList)
//TODO 6.使用功能方法groupBy将相同的单词分为一组
val wordGroupMap: Map[String, List[(String, Int)]] = word2OneList.groupBy(_._1)
//println(wordGroupMap)//Map(tom -> List((tom,1), (tom,1)),...)
//TODO 7.再次使用map映射
/*val wordCountMap: Map[String, Int] = wordGroupMap.map(
keyVal => { //keyVal是一个二元组 ,
// keyVal._1 就是key就是单词,_2对应List((tom,1), (tom,1)),List的size就是该单词出现的总次数
(keyVal._1, keyVal._2.size)
}
)*/
val wordCountMap: Map[String, Int] = wordGroupMap.map{
case (word,list) => (word,list.size)
}
println(wordCountMap)
//......
}
}