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();
相关推荐
_院长大人_1 小时前
设计模式-工厂模式
java·开发语言·设计模式
MATLAB代码顾问1 小时前
MATLAB实现决策树数值预测
开发语言·决策树·matlab
码事漫谈2 小时前
C++死锁深度解析:从成因到预防与避免
后端
码事漫谈2 小时前
智能体颠覆教育行业:现状、应用与未来展望调研报告
后端
蓝-萧2 小时前
【玩转全栈】----Django基本配置和介绍
java·后端
priority_key2 小时前
排序算法:堆排序、快速排序、归并排序
java·后端·算法·排序算法·归并排序·堆排序·快速排序
韩立学长2 小时前
基于Springboot的旧时月历史论坛4099k6s9(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
不染尘.2 小时前
2025_11_7_刷题
开发语言·c++·vscode·算法
似水এ᭄往昔2 小时前
【C++】--stack和queue
开发语言·c++
csbysj20203 小时前
R 绘图 - 散点图
开发语言