Map/Reduce编程作业

现有student.txt和student_score.txt。将两个文件上传到hdfs上。使用Map/Reduce框架完成下面的题目

student.txt

2016001,王毅
2016002,张小明
2016003,李学彭
2016004,王东
2016005,王笑笑

student_score.txt

2016001,操作系统,60
2016001,数据库,88
2016001,大数据概论,85
2016002,操作系统,91
2016002,大数据概论,91
2016003,大数据概论,56
2016003,操作系统,88
2016004,数据库,90
2016004,大数据概论,82
2016004,操作系统,78
2016005,操作系统,69
2016005,大数据概论,70
2016005,数据库,89

1)将stduent.txt和student_score.txt连接,输出学号、姓名、课程、分数字段。

2)统计每个同学的平均成绩,显示学号、姓名和平均成绩,并按照成绩高低降序排序。

3)统计每门课的最高分、最低分和平均分。

问题一:

StudentScore1.java

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class StudentScore1 { public static void main(String[] args) throws IllegalArgumentException, IOException, ClassNotFoundException, InterruptedException {
Configuration conf=new Configuration();
Job job=Job.getInstance(conf,"StudentScore1");
job.setJarByClass(StudentScore1.class); job.setMapperClass(ScoreMapper.class);
//Map的输出,避免程序不确定Map输出的值的类型不确定
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(SC.class); job.setReducerClass(ScoreReduce.class);
//输出类型
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(NullWritable.class); //数据来源
FileInputFormat.addInputPath(job,new Path("/StudentInput"));
//输出位置
FileOutputFormat.setOutputPath(job, new Path("/Output1")); System.exit(job.waitForCompletion(true)?0:1);
}
public static class ScoreMapper extends Mapper<Object, Text, Text, SC>{ @Override
protected void map(Object key, Text value, Mapper<Object, Text, Text, SC>.Context context)
throws IOException, InterruptedException {
//以“,”分割字符串
//Student 2016001,王毅 [2016001,王毅]
//Student_score 2016001,操作系统,60 [2016001,操作系统,60]
String[] words=value.toString().split(",");
//记录学号
String Sid=words[0];
SC sc=new SC();
//区分字符串属于那个类型
if(words.length==2) {//长度为2的记录信息是 学生
sc.setSid(Sid);
sc.setName(words[1]);
sc.setTable("Student");
context.write(new Text(Sid), sc);
}else {//长度为3的记录信息是 学科成绩
sc.setSid(Sid);
sc.setCourse(words[1]);
sc.setScore(Integer.parseInt(words[2]));
sc.setTable("Student_score");
context.write(new Text(Sid), sc);
} }
}
public static class ScoreReduce extends Reducer<Text, SC, Text, NullWritable>{ @Override
protected void reduce(Text key, Iterable<SC> values,
Reducer<Text, SC, Text,NullWritable>.Context context) throws IOException, InterruptedException { List<SC> list=new ArrayList<SC>();
String Name="";
//遍历结果集的value
for(SC value:values) { if(value.getTable().equals("Student")) {//只有姓名信息的记录下来
Name=value.getName();
}else {//否则,将其添加到待输出list中
SC sc=new SC();
try {
BeanUtils.copyProperties(sc, value);
list.add(sc);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}
//遍历list
for(SC sc:list) {
sc.setName(Name);
context.write(new Text(sc.toString()), NullWritable.get());
}
} }
}

SC.java

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException; import org.apache.hadoop.io.Writable; public class SC implements Writable{ private String Name="";
private String Sid="";
private String Course="";
private String Table="";
private int Score=0;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getSid() {
return Sid;
}
public void setSid(String sid) {
Sid = sid;
}
public String getCourse() {
return Course;
}
public void setCourse(String course) {
Course = course;
}
public String getTable() {
return Table;
}
public void setTable(String table) {
Table = table;
}
public int getScore() {
return Score;
}
public void setScore(int score) {
Score = score;
} @Override
public String toString() {
return Sid + "," + Name + "," + Course + "," + Score;
}
@Override
public void readFields(DataInput in) throws IOException {
this.Sid=in.readUTF();
this.Name=in.readUTF();
this.Course=in.readUTF();
this.Table=in.readUTF();
this.Score=in.readInt(); }
@Override
public void write(DataOutput out) throws IOException {
out.writeUTF(Sid);
out.writeUTF(Name);
out.writeUTF(Course);
out.writeUTF(Table);
out.writeInt(Score);
}
}

结果:

2016001,王毅,操作系统,60
2016001,王毅,数据库,88
2016001,王毅,大数据概论,85
2016002,张小明,操作系统,91
2016002,张小明,大数据概论,91
2016003,李学彭,操作系统,88
2016003,李学彭,大数据概论,56
2016004,王东,大数据概论,82
2016004,王东,操作系统,78
2016004,王东,数据库,90
2016005,王笑笑,数据库,89
2016005,王笑笑,操作系统,69
2016005,王笑笑,大数据概论,70

问题二:

Average2.java

import java.io.IOException;
import java.util.Comparator;
import java.util.TreeMap; import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class Average2 { public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Configuration conf=new Configuration();
Job job=Job.getInstance(conf,"Average2"); job.setJarByClass(Average2.class);
job.setMapperClass(Average2Mapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(DoubleWritable.class); job.setReducerClass(Average2Reduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(DoubleWritable.class); FileInputFormat.addInputPath(job, new Path("/Output1"));
FileOutputFormat.setOutputPath(job, new Path("/Output2"));
System.exit(job.waitForCompletion(true)?0:1); } public static class Average2Mapper extends Mapper<Object,Text,Text,DoubleWritable>{
@Override
protected void map(Object key, Text value, Mapper<Object, Text, Text, DoubleWritable>.Context context)
throws IOException, InterruptedException {
//分割
String[] words=value.toString().split(",");
//keybuf=[2016001,王毅,]
StringBuffer keybuf=new StringBuffer();
keybuf.append(words[0]).append(",").append(words[1]).append(",");
//score用来记录成绩
Double score=Double.parseDouble(words[3]);
context.write(new Text(keybuf.toString()), new DoubleWritable(score));
}
} public static class Average2Reduce extends Reducer<Text,DoubleWritable,Text,DoubleWritable>{
//new Comparetor<Double> 的方法 倒叙(从高到低)排序
private TreeMap<Double, String> treeMap=new TreeMap<Double, String>(new Comparator<Double>() {
@Override
public int compare(Double x, Double y) {
return y.compareTo(x);
}
}); @Override
protected void reduce(Text key, Iterable<DoubleWritable> values,
Reducer<Text, DoubleWritable, Text, DoubleWritable>.Context context)
throws IOException, InterruptedException {
//reduce的操作对象是[key,<value1,value2...>]
Double sumscore=0.0;
int num=0;
for(DoubleWritable value:values) {
num++;
sumscore=sumscore+value.get();
}
Double avg= sumscore/num;
//得到的结果先不输出,到treepMap里面先排个序
treeMap.put(avg, key.toString());
}
//输出
protected void cleanup(Context context) throws IOException, InterruptedException {
for(Double key:treeMap.keySet()) {
context.write(new Text(treeMap.get(key)), new DoubleWritable(key));
}
} }
}

结果:

2016002,张小明,	91.0
2016004,王东, 83.33333333333333
2016001,王毅, 77.66666666666667
2016005,王笑笑, 76.0
2016003,李学彭, 72.0

问题三:

Course3.java

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class Course3 { public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Configuration conf=new Configuration();
Job job=Job.getInstance(conf,"Course3"); job.setJarByClass(Course3.class);
job.setMapperClass(Course3Mapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class); job.setReducerClass(Course3Reduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class); FileInputFormat.addInputPath(job, new Path("/Output1"));
FileOutputFormat.setOutputPath(job, new Path("/Output3"));
System.exit(job.waitForCompletion(true)?0:1); } public static class Course3Mapper extends Mapper<Object,Text,Text,IntWritable>{ @Override
protected void map(Object key, Text value, Mapper<Object, Text,Text, IntWritable>.Context context)
throws IOException, InterruptedException {
//分割
String[] words=value.toString().split(",");
int Score=Integer.parseInt(words[3]);
//key=课程 value=某人某科成绩
context.write(new Text(words[2]), new IntWritable(Score)); }
} public static class Course3Reduce extends Reducer<Text,IntWritable,Text,Text>{ @Override
protected void reduce(Text key, Iterable<IntWritable> values,
Reducer<Text, IntWritable, Text, Text>.Context context) throws IOException, InterruptedException { int mmax=0;//最大值
int mmin=101;//最小值
double avg=0;//平均成绩
int num=0;//每科人数
for(IntWritable value:values) {
num++;
if(value.get()>mmax) mmax=value.get();
if(value.get()<mmin) mmin=value.get();
avg=avg+value.get();
}
avg=avg/num;
String score=String.valueOf(mmax)+","+String.valueOf(mmin)+","+String.valueOf(avg);
context.write(key,new Text(score));
}
}
}

结果:

大数据概论	91,56,76.8
操作系统 91,60,77.2
数据库 90,88,89.0

大数据作业之利用MapRedeuce实现简单的数据操作的更多相关文章

  1. 【SSH三大框架】Hibernate基础第五篇:利用Hibernate完毕简单的CRUD操作

    这里利用Hibernate操作数据库完毕简单的CRUD操作. 首先,我们须要先写一个javabean: package cn.itcast.domain; import java.util.Date; ...

  2. vue:使用不同参数跳转同一组件,实现动态加载图片和数据,以及利用localStorage和vuex持久化数据

    需求:通过不同的参数复用同一组件,实现动态加载数据和图片,同时,在页面刷新时,图片依旧可以加载成功. 过程出现的bug和问题: 1.使用params传参后,再次刷新页面,参数丢失导致数据无法再次加载 ...

  3. MVC4.0 利用IActionFilter实现简单的后台操作日志功能

    首先我们要了解MVC提供了4种常用的拦截器:IActionFilter(Action拦截器接口).IExceptionFilter(异常拦截器接口).IResultFilter(Result拦截器接口 ...

  4. memcache 存储单个KEY,数据量过大的时候性能慢!以及简单的memcache不适合用到的场景

    今天有人问到我:memcache存储大数据量,10K,100K,1M的时候,效果怎么样??我回答:不好,效果非常慢.对方问:为什么啊??我回答不上来...于是就找了点资料. memcached使用需要 ...

  5. 利用php的序列化和反序列化来做简单的数据本地存储

    利用php的序列化和反序列化来做简单的数据本地存储 如下程序可以做为一个工具类 /** * 利用php的序列化和反序列化来做简单的数据本地存储 */ class objectdb { private ...

  6. Java Web 开发利用Struts2+Spring+mybatis写一个用户登录界面以及简单的数据交互

    框架的东西太复杂也难以讲通,直接上代码: 一.首先得配置环境 和导入必要的jar包 有一些重要的如下: Filter文件夹下的SafetyFilter.java   model文件夹下的 Global ...

  7. 大数据学习day34---spark14------1 redis的事务(pipeline)测试 ,2. 利用redis的pipeline实现数据统计的exactlyonce ,3 SparkStreaming中数据写入Hbase实现ExactlyOnce, 4.Spark StandAlone的执行模式,5 spark on yarn

    1 redis的事务(pipeline)测试 Redis本身对数据进行操作,单条命令是原子性的,但事务不保证原子性,且没有回滚.事务中任何命令执行失败,其余的命令仍会被执行,将Redis的多个操作放到 ...

  8. 利用python进行数据分析之数据加载存储与文件格式

    在开始学习之前,我们需要安装pandas模块.由于我安装的python的版本是2.7,故我们在https://pypi.python.org/pypi/pandas/0.16.2/#downloads ...

  9. 利用python进行数据分析之数据规整化

    数据分析和建模大部分时间都用在数据准备上,数据的准备过程包括:加载,清理,转换与重塑. 合并数据集 pandas对象中的数据可以通过一些内置方法来进行合并: pandas.merge可根据一个或多个键 ...

随机推荐

  1. coding++:idea提交SVN或GIT时,忽略某些文件

    设置步骤:Settings→Editor→File Types在窗口最下方“Ignore files and folders”一栏中添加如下忽略: *.iml;*.idea;*.gitignore;* ...

  2. H - 遥远的糖果 HihoCoder - 1478

    给定一个N x M的01矩阵,其中1表示人,0表示糖.对于每一个位置,求出每个位置离糖的最短距离是多少. 矩阵中每个位置与它上下左右相邻的格子距离为1. Input 第一行包含两个整数,N和M. 以下 ...

  3. KVC讲解

    今天趁着项目bug修复完了,来讲解一下OC知识的另一个技术点-KVC!针对KVC,讲解两个知识点 通过KVC修改属性会触发KVO么? KVC的赋值过程是怎样的?原理是什么? KVC的取值过程是怎样的? ...

  4. Rust入坑指南:万物初始

    有没有同学记得我们一起挖了多少个坑?嗯-其实我自己也不记得了,今天我们再来挖一个特殊的坑,这个坑可以说是挖到根源了--元编程. 元编程是编程领域的一个重要概念,它允许程序将代码作为数据,在运行时对代码 ...

  5. WEB缓存系统之varnish代理以及健康状态检测配置

    前文我们聊了下varnish的缓存项修剪配置,回顾请参考https://www.cnblogs.com/qiuhom-1874/p/12666406.html:今天我来说一下varnish作为代理服务 ...

  6. Java8 学习笔记--函数式接口

    通过之前的函数式接口与lambda表达式的关系那篇文章,大家应该对函数式接口有了一定的了解了,在Java中它是lambda表达式的基础,没有函数式接口就没有办法使用lambda表达式. 函数式接口如此 ...

  7. Spring(二):初始值赋值

    依赖注入 1.构造器注入 见spring简介最后一大点. 2.Set方式注入 依赖注入:Set注入 依赖:bean对象的创建依赖于容器. 注入:bean对象的所有属性,由容器注入. bean ,里面属 ...

  8. java中查询某个类已经创建了多少个对象了

    这个代码主要是使用类的静态字段和构造函数,可以跟踪某个类所创建对象的个数.请写一个类,在任何时候都可以向它查询“你已经创建了多少个对象? 主要是在构造函数中用到了静态数据,进行显示已经构造了多少个类对 ...

  9. 面向对象核心技术(java)

    一.类的封装详解 在“面向对象编程基础(java)”的时候讲过,封装是面向对象编程的核心思想.同时我们也知道类是载体,只不过我们把对象的属性和行为封装在载体中. 现我们用封装的方式来实现,一个顾客去一 ...

  10. Javascript 入门 必备知识点

    1.如何得到html的input标签的值: (1). $('#id').val(); (2). $("#id").attr("value"); 2.javasc ...