• 4、Spark实例——WordCount


    代码1

    package com.bigdata.spark.core.WordCount
    
    import org.apache.spark.rdd.RDD
    import org.apache.spark.{SparkConf, SparkContext}
    
    object Spark01_WordCount {
    
      def main(args: Array[String]): Unit = {
    
        //TODO 建立和Spark框架的连接
        //JDBC : Connection
        var sparConf = new SparkConf().setMaster("local").setAppName("WordCount")
        val sc = new SparkContext(sparConf)
    
        //TODO 执行业务操作
        //1、读取文件,获得一行一行的数据
        val lines : RDD[String] = sc.textFile(path = "datas")
    
        //2、将一行数据进行拆分,形成一个一个的单词(分词)
        //扁平化 : 将整体拆分成个体的操作
        val words : RDD[String] = lines.flatMap(_.split(" "))
    
        //3、将数据根据单词进行分组,便于统计
        val wordGroup : RDD[(String,Iterable[String])]= words.groupBy(word => word)
    
        //4、对分组后的数据进行转换
        val wordToCount = wordGroup.map{
          case(word,list) => {
          (word,list.size)
        }
        }
    
        //5、将转换结果采集到控制台打印出来
        val array: Array[(String,Int)] = wordToCount.collect()
        array.foreach(println)
    
        //TODO 关闭连接
        sc.stop()
      }
    
    }
    

    代码2

    package com.bigdata.spark.core.WordCount
    
    import org.apache.spark.rdd.RDD
    import org.apache.spark.{SparkConf, SparkContext}
    
    object Spark02_WordCount {
      def main(args: Array[String]): Unit = {
    
        // Application
        // Spark框架
        // TODO 建立和Spark框架的连接
        // JDBC : Connection
        val sparConf = new SparkConf().setMaster("local").setAppName("WordCount")
        val sc = new SparkContext(sparConf)
    
        // TODO 执行业务操作
    
        // 1. 读取文件,获取一行一行的数据
        //    hello world
        val lines: RDD[String] = sc.textFile("datas")
    
        // 2. 将一行数据进行拆分,形成一个一个的单词(分词)
        //    扁平化:将整体拆分成个体的操作
        //   "hello world" => hello, world, hello, world
        val words: RDD[String] = lines.flatMap(_.split(" "))
    
        // 3. 将单词进行结构的转换,方便统计
        // word => (word, 1)
        val wordToOne = words.map(word=>(word,1))
    
        // 4. 将转换后的数据进行分组聚合
        // 相同key的value进行聚合操作
        // (word, 1) => (word, sum)
        val wordToSum: RDD[(String, Int)] = wordToOne.reduceByKey(_+_)
    
        // 5. 将转换结果采集到控制台打印出来
        val array: Array[(String, Int)] = wordToSum.collect()
        array.foreach(println)
    
        // TODO 关闭连接
        sc.stop()
    
      }
    }

  • 相关阅读:
    [LeetCode] Meeting Rooms I & II
    [LeetCode] Graph Valid Tree
    [LeetCode] Palindrome Permutation I & II
    [LeetCode] Encode and Decode Strings
    [LeetCode] Paint Fence
    android 发送短信功能
    andrioid 分享到其它(短信,qq,微信等功能)
    android Dialog实例
    android开发之onCreate( )方法详解
    android edittext属性说明
  • 原文地址:https://www.cnblogs.com/ltw222/p/15853505.html
Copyright © 2020-2023  润新知