Spark入门之WordCount

package com.core

import org.apache.spark.{SparkConf, SparkContext}


/**
  * Created by lxh on 2016/3/14.
  * 查看源码快捷键:CTRL + N
  *
  */
object WordCount {
  def main(args: Array[String]) {


    val conf = new SparkConf() //创建spark conf 对象
    conf.setAppName("WordCount app")
    conf.setMaster("local")
    val sc = new SparkContext(conf)
    sc.setLogLevel("WARN")

    val filepath = "D://testdata//helloSpark.txt"
    /**
      * 读取filepath的文件。分片数为1.
      */
    val lines = sc.textFile(filepath, 1)

    /**
      * 将行根据空格切割成词。
      */
    val words = lines.flatMap { lines => lines.split(" ") }

    /**
      * 将词转化为元组。出现一次计数为1.
      */
    val pairs = words.map { word => (word, 1) }


    /**
      * 将出现次数 累加。
      * 并且 转换(词,次数) 为(次数,词) 根据key——次数 进行排序。 然后重新转换成(词,次数)
      */
    val wordCountsOdered = pairs.reduceByKey(_ + _).map(pair => (pair._2, pair._1)).sortByKey(false).map(pair => (pair._2, pair._1))

    /**
      * 对每个元素进行打印输出。
      */
    wordCountsOdered.foreach(wordNumberPair => println(wordNumberPair._1 + "" + wordNumberPair._2))
    /* val wordCount = pairs.reduceByKey(_+_)
     wordCount.foreach(wordNumberPair => println(wordNumberPair._1+""+wordNumberPair._2 ))*/
    while (true){
      //循环,以便在web 控制台观察。
    }
    sc.stop()
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值