Scala---WordCount

一、创建Maven项目导入pom.xml文件

安装Maven仓库管理工具,版本要求是3.2版本以上。新建Maven项目,配置pom.xml。导入必要的包。

二、Spark-Scala版本的WordCount

1.val conf = new SparkConf()
2.conf.setMaster("local")
3.conf.setAppName("scala-wc")
4.val sc = new SparkContext(conf)
5.val lines = sc.textFile("./data/words")
6.val words = lines.flatMap(line=>{line.split(" ")})
7.val pairWords = words.map(word=>{new Tuple2(word,1)})
8.val result = pairWords.reduceByKey((v1:Int,v2:Int)=>{v1+v2})
9.result.foreach(println)

三、Spark-Java版本的WordCount

1.SparkConf conf = new SparkConf();
2.conf.setMaster("local");
3.conf.setAppName("java-wc");
4.JavaSparkContext sc = new JavaSparkContext(conf);
5.JavaRDD lines = sc.textFile("./data/words");
6.JavaRDD words = lines.flatMap(new   FlatMapFunction() {
7.  @Override
8.  public Iterator call(String s) throws Exception {
9.    String[] split = s.split(" ");
10.    return Arrays.asList(split).iterator();
11.  }
12.});
13.JavaPairRDD pairWords = words.mapToPair(new PairFunction() {
14.  @Override
15.  public Tuple2 call(String word) throws Exception {
16.    return new Tuple2<>(word, 1);
17.  }
18.});
19.JavaPairRDD result = pairWords.reduceByKey(new Function2() {
20.  @Override
21.  public Integer call(Integer v1, Integer v2) throws Exception {
22.    return v1 + v2;
23.  }
24.});
25.result.foreach(new VoidFunction>() {
26.  @Override
27.  public void call(Tuple2 tuple2) throws  Exception {
28.    System.out.println(tuple2);
29.  }
30.});
31.sc.stop();

你可能感兴趣的:(Scala,scala,开发语言,后端)