Spark之WordCount(Java代码实现)

本地模式:
`/**
* WordCountLocal.java
* com.majs.spark
* Copyright (c) 2017, majiashu版权所有.
* @author majiashu
*/

package com.majs.spark;

import java.util.Arrays;
import java.util.Iterator;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;

import scala.Tuple2;

/**
* @author majiashu
* @Date 2017年7月25日
*/
public class WordCountLocal {
public static void main(String[] args) {

    // 第一步:创建SparkConf对象,设置相关配置信息
    SparkConf conf = new SparkConf();
    conf.setAppName("wordcount");
    conf.setMaster("local");

    // 第二步:创建JavaSparkContext对象,SparkContext是Spark的所有功能的入口
    JavaSparkContext sc = new JavaSparkContext(conf);

    // 第三步:创建一个初始的RDD
    // SparkContext中,用于根据文件类型的输入源创建RDD的方法,叫做textFile()方法
    JavaRDD lines = sc.textFile("///C:/Users/majiashu/Desktop/text.txt");

    // 第四步:对初始的RDD进行transformation操作,也就是一些计算操作
    JavaRDD words = lines.flatMap(new FlatMapFunction() {

        private static final long serialVersionUID = 1L;

        @Override
        public Iterator call(String line) throws Exception {

            return Arrays.asList(line.split(" ")).iterator();

        }
    });
    JavaPairRDD pairs = words.mapToPair(new PairFunction() {

        /**
         * 
         */

        private static final long serialVersionUID = 1L;

        @Override
        public Tuple2 call(String word) throws Exception {
            return new Tuple2(word, 1);
        }
    });

    JavaPairRDD wordCounts = pairs.reduceByKey(new Function2() {

        private static final long serialVersionUID = 1L;

        @Override
        public Integer call(Integer v1, Integer v2) throws Exception {

            return v1 + v2;

        }
    });
    wordCounts.foreach(new VoidFunction>() {

        /**
         * 
         */

        private static final long serialVersionUID = 1L;

        @Override
        public void call(Tuple2 wordCount) throws Exception {
            System.out.println(wordCount._1 + "------" + wordCount._2+"times.");
        }
    });
    sc.close();

}

}
`

你可能感兴趣的:(spark)