scala算子应用汇总(持续更新)
新的 List 为原 List 每个元素的 平方和三次方
val list = List(1, 3, 5, 8, 11)
val list1 = list.flatMap(x => List(x, x * x, math.pow(x, 3).toInt))
println(list1) //List(1, 1, 1, 3, 9, 27, 5, 25, 125, 8, 64, 512, 11, 121, 1331)
1.词频统计
统计d:/test/wordcount.txt 下各单词出现的次数
//获取文件BufferedSource,这里因为Source需要close,所以跟后面分开了
val source = Source.fromFile("""d:/test/wordcount.txt""", "utf-8")
val wordCount =
source.getLines() //获取文本,每行为Iterator的一个元素
.toList //Iterator[String]没有groupby方法,所有需要转为List
.flatMap(_.split("\\W+")) //使用非文本字符进行切割,为什么切割之后会有空字符?(非单词字符,等价于 [^A-Z a-z 0-9_],应该没有空字符啊)
.filter(_.length>