用scala实现wordcount例子
为了简便,直接对字符串进行操作,没有读取文件。
大致思路都在代码里了
参考了这篇博客的思路,传送门
object WordCount {
def main(args: Array[String]): Unit = {
val str1 ="hello world"
val str2 ="hello scala java jvm"
val list =List(str1,str2)
/**
* 首先分割字符串 split
* 映射成 Tuple2 map(_,1)
* 对tuple 进行按key分组
* 在组内进行value端求和
* 最后打印
*/
list.flatMap(_.split(" ")).map((_,1)).groupBy(_._1).mapValues(_.map(_._2).reduce(_+_)).foreach(println _)
}
}
ps:
写在最后,学习新的一门语言主要是语法问题,我都不知道还有mapValues这种操作,多练习吧!打下spark基础