面向函数编程
wordcount练习
package scala
import scala.io.{BufferedSource, Source}
object Demo11WordCount {
def main(args: Array[String]): Unit = {
//1.读取文件
val source: BufferedSource = Source.fromFile("data/words.txt")
//转换成集合
val list: List[String] = source.getLines().toList
// println(list)
//2.将每一行的代码拆分出来,一行转多行
val str: List[String] = list.flatMap((f:String)=>f.split(","))
//println(str)
//3.按照单词进行分组
//key 是单词,value 是单词的集合
val group: Map[String, List[String]] = str.groupBy((f:String)=>f)
//group.foreach(println)
//4.统计单词数量,也即是统计集合的长度
val stringToInt: Map[String, Int] = group.map((f: (String, List[String])) => {
val word: String = f._1
val count: List[String] = f._2
val length: Int = count.length
(word, length)
})
stringToInt.foreach(println)
//缩写
Source
.fromFile("data/words.txt")
.getLines()
.toList
.flatMap(_.split(","))
.groupBy(f => f)
.mapValues(_.length)
}
}