不多说,直接上代码。

  统计出每个年龄段的 男、女 学生的最高分

  这里,为了空格符的差错,直接,我们有时候,像如下这样的来排数据。

代码

package zhouls.bigdata.myMapReduce.Gender;

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
*
* @function 统计不同年龄段内 男、女最高分数
*
*
*/ /*
Alice<tab>23<tab>female<tab>45
Bob<tab>34<tab>male<tab>89
Chris<tab>67<tab>male<tab>97
Kristine<tab>38<tab>female<tab>53
Connor<tab>25<tab>male<tab>27
Daniel<tab>78<tab>male<tab>95
James<tab>34<tab>male<tab>79
Alex<tab>52<tab>male<tab>69
Nancy<tab>7<tab>female<tab>98
Adam<tab>9<tab>male<tab>37
Jacob<tab>7<tab>male<tab>23
Mary<tab>6<tab>female<tab>93
Clara<tab>87<tab>female<tab>72
Monica<tab>56<tab>female<tab>92
*/
public class Gender extends Configured implements Tool {
/*
*
* @function Mapper 解析输入数据,然后按需求输出
* @input key=行偏移量 value=学生数据
* @output key=gender value=name+age+score
*
*/
public static class PCMapper extends Mapper<Object, Text, Text, Text>
{
public void map(Object key, Text value, Context context) throws IOException, InterruptedException
{//拿Alice<tab>23<tab>female<tab>45
String[] tokens = value.toString().split("<tab>");//使用分隔符<tab>,将数据解析为数组 tokens
//得到Alice 23 female 45
//即tokens[0] tokens[1] tokens[2] tokens[3]
String gender = tokens[].toString();//性别
String nameAgeScore = tokens[] + "\t" + tokens[] + "\t"+ tokens[];
//输出 key=gender value=name+age+score
//输出 key=female value=Alice +23+45
context.write(new Text(gender), new Text(nameAgeScore));//将 (female , Alice+ 23+ 45) 写入到context中
}
}
public static class MyHashPartitioner extends Partitioner<Text, Text>
{
/** Use {@link Object#hashCode()} to partition. */
@Override
public int getPartition(Text key, Text value,int numReduceTasks)
{
return (key.hashCode()) % numReduceTasks;
} }
/**
*
* @function Partitioner 根据 age 选择 reduce 分区
*
*/
public static class PCPartitioner extends Partitioner<Text, Text>
{ @Override
public int getPartition(Text key, Text value, int numReduceTasks)
{
// TODO Auto-generated method stub
String[] nameAgeScore = value.toString().split("\t");
String age = nameAgeScore[];//学生年龄
int ageInt = Integer.parseInt(age);//按年龄段分区 // 默认指定分区 0
if (numReduceTasks == )
return ; //年龄小于等于20,指定分区0
if (ageInt <= ) {
return ;
}
// 年龄大于20,小于等于50,指定分区1
if (ageInt > && ageInt <= ) { return % numReduceTasks;
}
// 剩余年龄,指定分区2
else
return % numReduceTasks;
}
} /**
*
* @function 定义Combiner 合并 Mapper 输出结果
*
*/
public static class PCCombiner extends Reducer<Text, Text, Text, Text>
{
private Text text = new Text(); public void reduce(Text key, Iterable<Text> values, Context context)throws IOException, InterruptedException
{
int maxScore = Integer.MIN_VALUE;
String name = " ";
String age = " ";
int score = ;
for (Text val : values)
{
String[] valTokens = val.toString().split("\\t");
score = Integer.parseInt(valTokens[]);
if (score > maxScore)
{
name = valTokens[];
age = valTokens[];
maxScore = score;
}
}
text.set(name + "\t" + age + "\t" + maxScore);
context.write(key, text);
}
} /*
*
* @function Reducer 统计出 不同年龄段、不同性别 的最高分
* input key=gender value=name+age+score
* output key=name value=age+gender+score
*
*/
static class PCReducer extends Reducer<Text, Text, Text, Text>
{
@Override
public void reduce(Text key, Iterable<Text> values, Context context)throws IOException, InterruptedException
{
int maxScore = Integer.MIN_VALUE;
String name = " ";
String age = " ";
String gender = " ";
int score = ;
// 根据key,迭代 values 集合,求出最高分
for (Text val : values)
{
String[] valTokens = val.toString().split("\\t");
score = Integer.parseInt(valTokens[]);
if (score > maxScore)
{
name = valTokens[];
age = valTokens[];
gender = key.toString();
maxScore = score;
}
}
context.write(new Text(name), new Text("age- " + age + "\t" + gender + "\tscore-" + maxScore));
}
} /**
* @function 任务驱动方法
* @param args
* @return
* @throws Exception
*/
@Override
public int run(String[] args) throws Exception
{
// TODO Auto-generated method stub
Configuration conf = new Configuration();//读取配置文件 Path mypath = new Path(args[]);
FileSystem hdfs = mypath.getFileSystem(conf);
if (hdfs.isDirectory(mypath))
{
hdfs.delete(mypath, true);
} @SuppressWarnings("deprecation")
Job job = new Job(conf, "gender");//新建一个任务
job.setJarByClass(Gender.class);//主类
job.setMapperClass(PCMapper.class);//Mapper
job.setReducerClass(PCReducer.class);//Reducer job.setPartitionerClass(MyHashPartitioner.class);
//job.setPartitionerClass(PCPartitioner.class);//设置Partitioner类
job.setNumReduceTasks();// reduce个数设置为3 job.setMapOutputKeyClass(Text.class);//map 输出key类型
job.setMapOutputValueClass(Text.class);//map 输出value类型 job.setCombinerClass(PCCombiner.class);//设置Combiner类 job.setOutputKeyClass(Text.class);//输出结果 key类型
job.setOutputValueClass(Text.class);//输出结果 value 类型 FileInputFormat.addInputPath(job, new Path(args[]));// 输入路径
FileOutputFormat.setOutputPath(job, new Path(args[]));// 输出路径
job.waitForCompletion(true);//提交任务
return ;
}
/**
* @function main 方法
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
// String[] args0 = {
// "hdfs://HadoopMaster:9000/gender/gender.txt",
// "hdfs://HadoopMaster:9000/out/partition/" }; String[] args0 = {
"./data/gender/gender.txt",
"./out/gender" }; int ec = ToolRunner.run(new Configuration(),new Gender(), args0);
System.exit(ec);
}
}

    或者

    代码

package com.dajiangtai.hadoop.junior;

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
*
* @function 统计不同年龄段内 男、女最高分数
* @author zhouls
*
*/ /*
Alice<tab>23<tab>female<tab>45
Bob<tab>34<tab>male<tab>89
Chris<tab>67<tab>male<tab>97
Kristine<tab>38<tab>female<tab>53
Connor<tab>25<tab>male<tab>27
Daniel<tab>78<tab>male<tab>95
James<tab>34<tab>male<tab>79
Alex<tab>52<tab>male<tab>69
Nancy<tab>7<tab>female<tab>98
Adam<tab>9<tab>male<tab>37
Jacob<tab>7<tab>male<tab>23
Mary<tab>6<tab>female<tab>93
Clara<tab>87<tab>female<tab>72
Monica<tab>56<tab>female<tab>92
*/
public class Gender extends Configured implements Tool {
/*
*
* @function Mapper 解析输入数据,然后按需求输出
* @input key=行偏移量 value=学生数据
* @output key=gender value=name+age+score
*
*/
public static class PCMapper extends Mapper<Object, Text, Text, Text>
{
public void map(Object key, Text value, Context context) throws IOException, InterruptedException
{//拿Alice<tab>23<tab>female<tab>45
String[] tokens = value.toString().split("<tab>");//使用分隔符<tab>,将数据解析为数组 tokens
//得到Alice 23 female 45
//即tokens[0] tokens[1] tokens[2] tokens[3]
String gender = tokens[].toString();//性别
String nameAgeScore = tokens[] + "\t" + tokens[] + "\t"+ tokens[];
//输出 key=gender value=name+age+score
//输出 key=female value=Alice +23+45
context.write(new Text(gender), new Text(nameAgeScore));//将 (female , Alice+ 23+ 45) 写入到context中
}
}
public static class MyHashPartitioner extends Partitioner<Text, Text>
{
/** Use {@link Object#hashCode()} to partition. */
@Override
public int getPartition(Text key, Text value,int numReduceTasks)
{
return (key.hashCode()) % numReduceTasks;
} }
/**
*
* @function Partitioner 根据 age 选择 reduce 分区
*
*/
public static class PCPartitioner extends Partitioner<Text, Text>
{ @Override
public int getPartition(Text key, Text value, int numReduceTasks)
{
// TODO Auto-generated method stub
String[] nameAgeScore = value.toString().split("\t");
String age = nameAgeScore[];//学生年龄
int ageInt = Integer.parseInt(age);//按年龄段分区 // 默认指定分区 0
if (numReduceTasks == )
return ; //年龄小于等于20,指定分区0
if (ageInt <= ) {
return ;
}
// 年龄大于20,小于等于50,指定分区1
if (ageInt > && ageInt <= ) { return % numReduceTasks;
}
// 剩余年龄,指定分区2
else
return % numReduceTasks;
}
} /**
*
* @function 定义Combiner 合并 Mapper 输出结果
*
*/
public static class PCCombiner extends Reducer<Text, Text, Text, Text>
{
private Text text = new Text(); public void reduce(Text key, Iterable<Text> values, Context context)throws IOException, InterruptedException
{
int maxScore = Integer.MIN_VALUE;
String name = " ";
String age = " ";
int score = ;
for (Text val : values)
{
String[] valTokens = val.toString().split("\\t");
score = Integer.parseInt(valTokens[]);
if (score > maxScore)
{
name = valTokens[];
age = valTokens[];
maxScore = score;
}
}
text.set(name + "\t" + age + "\t" + maxScore);
context.write(key, text);
}
} /*
*
* @function Reducer 统计出 不同年龄段、不同性别 的最高分
* input key=gender value=name+age+score
* output key=name value=age+gender+score
*
*/
static class PCReducer extends Reducer<Text, Text, Text, Text>
{
@Override
public void reduce(Text key, Iterable<Text> values, Context context)throws IOException, InterruptedException
{
int maxScore = Integer.MIN_VALUE;
String name = " ";
String age = " ";
String gender = " ";
int score = ;
// 根据key,迭代 values 集合,求出最高分
for (Text val : values)
{
String[] valTokens = val.toString().split("\\t");
score = Integer.parseInt(valTokens[]);
if (score > maxScore)
{
name = valTokens[];
age = valTokens[];
gender = key.toString();
maxScore = score;
}
}
context.write(new Text(name), new Text("age- " + age + "\t" + gender + "\tscore-" + maxScore));
}
} /**
* @function 任务驱动方法
* @param args
* @return
* @throws Exception
*/
@Override
public int run(String[] args) throws Exception
{
// TODO Auto-generated method stub
Configuration conf = new Configuration();//读取配置文件 Path mypath = new Path(args[]);
FileSystem hdfs = mypath.getFileSystem(conf);
if (hdfs.isDirectory(mypath))
{
hdfs.delete(mypath, true);
} @SuppressWarnings("deprecation")
Job job = new Job(conf, "gender");//新建一个任务
job.setJarByClass(Gender.class);//主类
job.setMapperClass(PCMapper.class);//Mapper
job.setReducerClass(PCReducer.class);//Reducer job.setPartitionerClass(MyHashPartitioner.class);
//job.setPartitionerClass(PCPartitioner.class);//设置Partitioner类
job.setNumReduceTasks();// reduce个数设置为3 job.setMapOutputKeyClass(Text.class);//map 输出key类型
job.setMapOutputValueClass(Text.class);//map 输出value类型 job.setCombinerClass(PCCombiner.class);//设置Combiner类 job.setOutputKeyClass(Text.class);//输出结果 key类型
job.setOutputValueClass(Text.class);//输出结果 value 类型 FileInputFormat.addInputPath(job, new Path(args[]));// 输入路径
FileOutputFormat.setOutputPath(job, new Path(args[]));// 输出路径
job.waitForCompletion(true);//提交任务
return ;
}
/**
* @function main 方法
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
String[] args0 = {
"hdfs://master:9000/middle/partition/gender.txt",
"hdfs://master:9000/middle/partition/out/" };
int ec = ToolRunner.run(new Configuration(),new Gender(), args0);
System.exit(ec);
}
}

Hadoop MapReduce编程 API入门系列之统计学生成绩版本2(十八)的更多相关文章

  1. Hadoop MapReduce编程 API入门系列之压缩和计数器(三十)

    不多说,直接上代码. Hadoop MapReduce编程 API入门系列之小文件合并(二十九) 生成的结果,作为输入源. 代码 package zhouls.bigdata.myMapReduce. ...

  2. Hadoop MapReduce编程 API入门系列之挖掘气象数据版本2(十)

    下面,是版本1. Hadoop MapReduce编程 API入门系列之挖掘气象数据版本1(一) 这篇博文,包括了,实际生产开发非常重要的,单元测试和调试代码.这里不多赘述,直接送上代码. MRUni ...

  3. Hadoop MapReduce编程 API入门系列之挖掘气象数据版本3(九)

    不多说,直接上干货! 下面,是版本1. Hadoop MapReduce编程 API入门系列之挖掘气象数据版本1(一) 下面是版本2. Hadoop MapReduce编程 API入门系列之挖掘气象数 ...

  4. Hadoop MapReduce编程 API入门系列之小文件合并(二十九)

    不多说,直接上代码. Hadoop 自身提供了几种机制来解决相关的问题,包括HAR,SequeueFile和CombineFileInputFormat. Hadoop 自身提供的几种小文件合并机制 ...

  5. Hadoop MapReduce编程 API入门系列之薪水统计(三十一)

    不多说,直接上代码. 代码 package zhouls.bigdata.myMapReduce.SalaryCount; import java.io.IOException; import jav ...

  6. Hadoop MapReduce编程 API入门系列之MapReduce多种输入格式(十七)

    不多说,直接上代码. 代码 package zhouls.bigdata.myMapReduce.ScoreCount; import java.io.DataInput; import java.i ...

  7. Hadoop MapReduce编程 API入门系列之Crime数据分析(二十五)(未完)

    不多说,直接上代码. 一共12列,我们只需提取有用的列:第二列(犯罪类型).第四列(一周的哪一天).第五列(具体时间)和第七列(犯罪场所). 思路分析 基于项目的需求,我们通过以下几步完成: 1.首先 ...

  8. Hadoop MapReduce编程 API入门系列之计数器(二十七)

    不多说,直接上代码. MapReduce 计数器是什么?    计数器是用来记录job的执行进度和状态的.它的作用可以理解为日志.我们可以在程序的某个位置插入计数器,记录数据或者进度的变化情况. Ma ...

  9. Hadoop MapReduce编程 API入门系列之join(二十六)(未完)

    不多说,直接上代码. 天气记录数据库 Station ID Timestamp Temperature 气象站数据库 Station ID Station Name 气象站和天气记录合并之后的示意图如 ...

随机推荐

  1. 安卓桌布显示的dip和px

    安卓程序设计界面显示设置图像大小,在layout.xml里面有dip和px选项,dip为 什么 暂时还不知道,或许是设计桌布的设定像素比率,px为像素值: 比如我的手机是 Lenovo K920,屏幕 ...

  2. 【sqli-labs】 less43 POST -Error based -String -Stacked with tiwst(POST型基于错误的堆叠变形字符型注入)

    和less42一样 login_user=&login_password=1');insert into users(id,username,password) value(15,'root' ...

  3. mount 命令总结

    配置CnetOS 7.4 本地yum源,记录下遇到的ISO镜像挂载问题,使用 blkid 命令可以查看设备的UUID.Label.文件系统类型(iso镜像文件系统类型iso9660) [root@lo ...

  4. Dart 调用C语言混合编程

    Dart 调用C语言本篇博客研究Dart语言如何调用C语言代码混合编程,最后我们实现一个简单示例,在C语言中编写简单加解密函数,使用dart调用并传入字符串,返回加密结果,调用解密函数,恢复字符串内容 ...

  5. 简单说基于JWT和appkey、sercurtyKey的SSO、身份认证方案

    环境介绍, 一个大的系统由多个子系统组成.典型地,假设有一个平台,其上接入了多个应用.则有几个常见的问题需要处理, 1.SSO(包括单个应用退出时,需要处理为整个系统退出): 2.平台跳转到应用.及应 ...

  6. (10)Spring Boot修改端口号【从零开始学Spring Boot】

    Spring boot 默认端口是8080,如果想要进行更改的话,只需要修改applicatoin.properties文件,在配置文件中加入: server.port=9090 常用配置: #### ...

  7. 使用 F# 列表

    使用 F# 列表 在 C# 中使用 F# 的列表,是全然可能的,可是,我建议不要用,由于,仅仅要再做一点,就会使事情在 C# 看来更加自然.比如,把列表转换成数组非常easy.用List.toArra ...

  8. Java中Void占位符的測试及个人理解

    Java对Void类的说明是:Void 类是一个不可实例化的占位符类,它保持一个对代表 Java keyword void 的 Class 对象的引用. 代表的是: 代表主要的 Java 类型 voi ...

  9. 【翻译自mos文章】ABMR:在asm 环境中測试Automatic Block Recover 特性的方法

    ABMR:在asm 环境中測试Automatic Block Recover 特性的方法 參考原文: ABMR: How to test Automatic Block Recover Feature ...

  10. 怎样又一次编译linux内核

    linux作为自由软件.在广大爱好者的支持下,内核版本号不断更新. 新的内核修订了就得内核的bug,并添加了很多新的特性.假设用户须要使用这些新的特性或者依据自己的系统量身定做一个更高效或更稳定的内核 ...