object WordCount{
def main(args: Array[String]): Unit = {
val conf = new SparkConf().setAppName("wordcount")
val sc = new SparkContext(conf)
sc.textFile(args(0)).flatMap(_.split(" ")).map((_, 1)).reduceByKey(_+_).collect
sc.stop()
}
}
textFile(args(0)):读取args(0)指定的文件里的数据;
flatMap(_.split(" ")):压平操作,按照空格分割符将每行数据映射成一个个单词;
map((_,1)):对每一个元素(单词)操作,将单词映射为元组;
reduceByKey(_+_):按照key将值进行聚合,相同key的value进行相加;
collect:将数据收集到Driver端展示。
下面的代码不仅实现了wordcount,还将结果按照单词出现的个数降序,并保存到args(1)所指定的文件里
object WordCount2{
def main(args: Array[String]): Unit = {
val conf = new SparkConf().setAppName("wordcount2")
val sc = new SparkContext(conf)
sc.textFile(args(0)).flatMap(_.split(" ")).map((_, 1)).reduceByKey(_+_).sortBy(_._2, false).saveAsTextFile(args(1))
sc.stop()
}
}