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<String> lines = sc.textFile("./data/words");
6.JavaRDD<String> words = lines.flatMap(new   FlatMapFunction<String, String>() {
7.  @Override
8.  public Iterator<String> call(String s) throws Exception {
9.    String[] split = s.split(" ");
10.    return Arrays.asList(split).iterator();
11.  }
12.});
13.JavaPairRDD<String, Integer> pairWords = words.mapToPair(new PairFunction<String, String, Integer>() {
14.  @Override
15.  public Tuple2<String, Integer> call(String word) throws Exception {
16.    return new Tuple2<>(word, 1);
17.  }
18.});
19.JavaPairRDD<String, Integer> result = pairWords.reduceByKey(new Function2<Integer, Integer, Integer>() {
20.  @Override
21.  public Integer call(Integer v1, Integer v2) throws Exception {
22.    return v1 + v2;
23.  }
24.});
25.result.foreach(new VoidFunction<Tuple2<String, Integer>>() {
26.  @Override
27.  public void call(Tuple2<String, Integer> tuple2) throws  Exception {
28.    System.out.println(tuple2);
29.  }
30.});
31.sc.stop();
相关推荐
yukai080084 分钟前
Python一些可能用的到的函数系列130 UCS-Time Brick
开发语言·python
细心的莽夫5 分钟前
集合复习(java)
java·开发语言·笔记·学习·java-ee
卫卫周大胖;7 分钟前
【C++】多态(详解)
开发语言·c++
yours_Gabriel11 分钟前
java基础:面向对象(二)
java·开发语言·笔记·学习
Enaium14 分钟前
Rust入门实战 编写Minecraft启动器#3解析资源配置
java·开发语言·rust
我写代码菜如坤15 分钟前
Unity中遇到“Input Button unload_long_back_btn is not setup”问题
开发语言
许思王28 分钟前
【Python】组合数据类型:序列,列表,元组,字典,集合
开发语言·人工智能·python
虫小宝1 小时前
如何在Java中实现PDF生成
java·开发语言·pdf
Java4ye1 小时前
Netty 是如何解析 Redis RESP 协议的——请求篇
后端
菜鸡且互啄692 小时前
在线教育平台,easyexcel使用案例
java·开发语言