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();
相关推荐
异常君4 分钟前
Redis 中的概率过滤器:布隆过滤器与布谷鸟过滤器实战对比
java·redis·后端
Stimd7 分钟前
【重写SpringFramework】声明式事务上:构建事务切面(chapter 4-5)
java·后端·spring
雷渊13 分钟前
深入分析dubbo的整体架构
后端
我是苏苏15 分钟前
消息中间件RabbitMQ02:账号的注册、点对点推送信息
开发语言·后端·ruby
weixin_4565881515 分钟前
【Spring Boot】Maven中引入 springboot 相关依赖的方式
spring boot·后端·maven
追逐时光者24 分钟前
C#/.NET/.NET Core技术前沿周刊 | 第 36 期(2025年4.21-4.27)
后端·.net
写bug写bug32 分钟前
Java并发编程:优雅的关闭钩子(Shutdown Hook)
java·后端
工藤新一¹33 分钟前
C++/SDL 进阶游戏开发 —— 双人塔防(代号:村庄保卫战 14)
开发语言·c++·游戏引擎·游戏开发·sdl·实践项目
钢铁男儿40 分钟前
C#核心技术解析:静态类型、dynamic与可空类型
开发语言·c#
noravinsc1 小时前
django filter 排除字段
后端·python·django