Hadoop MapReduce编程 API入门系列之统计学生成绩版本2(十八)

2023-05-16

 

  不多说,直接上代码。

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

 

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

代码


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[2].toString();//性别
String nameAgeScore = tokens[0] + "\t" + tokens[1] + "\t"+ tokens[3];
//输出 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[1];//学生年龄
int ageInt = Integer.parseInt(age);//按年龄段分区

// 默认指定分区 0
if (numReduceTasks == 0)
return 0;

//年龄小于等于20,指定分区0
if (ageInt <= 20) {
return 0;
}
// 年龄大于20,小于等于50,指定分区1
if (ageInt > 20 && ageInt <= 50) {

return 1 % numReduceTasks;
}
// 剩余年龄,指定分区2
else
return 2 % 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 = 0;
for (Text val : values) 
{
String[] valTokens = val.toString().split("\\t");
score = Integer.parseInt(valTokens[2]);
if (score > maxScore) 
{
name = valTokens[0];
age = valTokens[1];
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 = 0;
// 根据key,迭代 values 集合,求出最高分
for (Text val : values)
{
String[] valTokens = val.toString().split("\\t");
score = Integer.parseInt(valTokens[2]);
if (score > maxScore) 
{
name = valTokens[0];
age = valTokens[1];
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[1]);
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(3);// 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[0]));// 输入路径
FileOutputFormat.setOutputPath(job, new Path(args[1]));// 输出路径
job.waitForCompletion(true);//提交任务
return 0;
}
/**
* @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[2].toString();//性别
            String nameAgeScore = tokens[0] + "\t" + tokens[1] + "\t"+ tokens[3];
            //输出  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[1];//学生年龄
            int ageInt = Integer.parseInt(age);//按年龄段分区

            // 默认指定分区 0
            if (numReduceTasks == 0)
                return 0;

            //年龄小于等于20,指定分区0
            if (ageInt <= 20) {
                return 0;
            }
            // 年龄大于20,小于等于50,指定分区1
            if (ageInt > 20 && ageInt <= 50) {

                return 1 % numReduceTasks;
            }
            // 剩余年龄,指定分区2
            else
                return 2 % 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 = 0;
            for (Text val : values) 
            {
                String[] valTokens = val.toString().split("\\t");
                score = Integer.parseInt(valTokens[2]);
                if (score > maxScore) 
                {
                    name = valTokens[0];
                    age = valTokens[1];
                    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 = 0;
            // 根据key,迭代 values 集合,求出最高分
            for (Text val : values)
                {
                String[] valTokens = val.toString().split("\\t");
                score = Integer.parseInt(valTokens[2]);
                if (score > maxScore) 
                {
                    name = valTokens[0];
                    age = valTokens[1];
                    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[1]);
        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(3);// 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[0]));// 输入路径
        FileOutputFormat.setOutputPath(job, new Path(args[1]));// 输出路径
        job.waitForCompletion(true);//提交任务
        return 0;
    }
    /**
     * @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);
    }
}  

 

转载于:https://www.cnblogs.com/zlslch/p/6165704.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

  • Linux系统-CENTOS7界面美化

    前期准备 xff1a 在美化前 我们先安装一个扩展源 yum install y epel release 然后安装字体包 yum y install liberation mono fonts 安装gnome menis标准菜单实现 通常
  • [原创]Python+selenium+Chrome爬取excel网站

    最近要写一个水利网站的爬虫脚本 xff0c 将网页中2个excel的数据 xff0c 爬到一个excel表里 恩 xff0c 就是下面的网页截图 xff0c 一左一右两张表 左边日期控件 xff0c 输入对应日期查询相应日期的数据 看到这么
  • el-select绑定值为对象时,报错[Vue warn]: <transition-group> children must be keyed: <ElTag>...

    解决方法 xff1a lt el select v model 61 34 syncParams toSlaveList 34 multiple value key 61 34 ip 34 placeholder 61 34 请选择 34
  • iOS开发零基础教程之真机调试流程

    本讲主要内容 xff1a 1 真机测试前准备工作 2 第一步创建App ID 3 第二步创建开发证书Development Certificate 4 第三步打开本地钥匙串创建CSR文件 5 第四步添加设备 6 第五步创建描述文件 7 第六
  • OVN简介

    三 OVN入门 3 1 OVN简介 Open vSwitch xff08 OVS xff09 是一款开源的 虚拟交换机 xff0c 控制协议方面它不但支持OpenFlow的所有特性而且扩展了部分OpenFlow的功能 xff1b Overl
  • 压缩 质量不变_项目启动后客户要求压缩工期,该如何处理?

    点击蓝字关注我们 马先生 首先 xff0c 项目经理应了解这种要求的合理性和必要性 xff0c 如果甲方确实有充分和充足的需要 xff0c 再进行如下工作 xff1a 1 组织项目团队认真分析赶工的可行性 xff0c 如果可行 xff0c
  • 第八章 让开发板发出声音,蜂鸣器驱动 心得体会

    第8章让开发板发出声音 xff0c 蜂鸣器驱动 心得体会 通过学习Android深度探索 卷1 HAL与驱动开发的第8章 让开发板发出声音 xff0c 蜂鸣器驱动 xff0c 我加深对驱动的认识 以下主要是我对本节实验和参考在Linux驱动
  • 连接到CentOS(Linux)服务器ssh、mysql缓慢

    现象 xff1a 服务器163与服务器164在同一机柜 xff0c 双绞线直接连接 xff0c 从办公室或者服务器163去连机服务器164的ssh mysql均缓慢 xff0c 让机房人员查了 xff0c 无果 而164却正常 最后发现两个
  • vs 下调试 引用的DLL源码

    在开发时 xff0c 可以经常引用带源码的DLL xff0c 但有时可以又要跟踪到源码里 解决 xff1a 1 引用Debug目录下的DLL xff0c 不要引用Release目录下的DLL 当然被引用的DLL项目 xff0c 要在Debu
  • 从SDN鼻祖Nicira到VMware NSX 网络虚拟化平台的简单探讨

    以前的大二层技术 xff0c 一般是在物理网络底层使用IS IS路由技术 xff0c 再在此基础之上 xff0c 实现数据中心网络的二层扩展 xff0c 如公有的Trill SPB技术和Cisco私有的OTV Fabricpath技术 xf
  • 使用mysqladmin命令修改Mysql密码

    1 例如你的 root用户现在没有密码 xff0c 你希望的密码修改为123456 xff0c 那么命令是 xff1a mysqladmin u root password 123456 2 如果你的root现在有密码了 xff08 123
  • pyqt5——菜单和工具栏

    菜单和工具栏 这个章节 xff0c 我们会创建状态栏 菜单和工具栏 菜单是一组位于菜单栏的命令 工具栏是应用的一些常用工具按钮 状态栏显示一些状态信息 xff0c 通常在应用的底部 主窗口 QMainWindow提供了主窗口的功能 xff0
  • linux cuda安装目录,ubuntu16.04上的cuda安装、卸载以及替换

    以cuda9 0为例 xff1a 安装 首先 xff0c 下载对应版本的cuda的运行脚本 xff0c 我下载的是cuda 9 0 176 384 91 linux run 1 运行脚本文件sudo sh cuda 9 0 176 384
  • C++软件工程师,你该会什么?

    请尊重原创 转载注明来源 原创在这里哦 C语言广泛用于基础软件 桌面系统 网络通信 音频视频 游戏娱乐等诸多领域 是世界上使用最广泛的编程语言之一 随着物联网技术的发展 xff0c C C 43 43 技术在3G 网络通信 xff08 移动
  • 芒果iOS开发面试题答案

    面试题答案总结 1 简述OC中内存管理机制 1 1 OC的内存管理机制是自动引用计数 xff0c 内存管理的原则是谁开辟谁释放 xff0c 有retain的地方就要有release 1 2 内存管理分为ARC和MRC xff0c 在MRC下
  • 软件工程概论-----课后作业一

    1 网站系统开发需要掌握的技术 xff1f 答 xff1a 网站的开发技术有很多 xff0c 主要包括CGI ASP PHP JSP ASP xff0e NET等 每一种技术都有其自身的特点与局限性 xff0c 具体的网站开发技术要根据网站
  • 拒绝拖延,立即行动 拥有积极心态的四大秘诀

    自己是一个非常拖延的人 在网上找了些指导的文章 用来自勉 以期付出行动 改正自己的坏习惯 根据心理学家的统计 xff0c 每个人每天大约会产生5万个想法 如果你拥有积极的态度 xff0c 那么你就能乐观地 富有创造力地把这5万个想法转换成正
  • STM32 F4 任务创建的步骤

    跟任务重要的三个参数 任务函数 任务堆栈 任务控制块 其他参数 stk limit 任务堆栈深度限位 栈深 确保堆栈不溢出 一般的为堆栈大小的1 10 QTY 内建的消息队列 OS TICK 时间轮转 OS OPT 选项 监测任务堆栈 允许
  • ubuntu下能ping通ssh不通的解决思路

    1 首先看看是否能ping通 xff0c 如果ping不通可能就要考虑网线 路由等问题了 xff1b 2 看防火墙是否关闭 xff0c sshd是否开启 3 ssh v 服务器的ip号 xff0c 根据提示寻找可能的问题 xff1b 我的问
  • lu分解法matlab_MATLAB因式分解

    4 1 因式分解 本节介绍线性代数的一些基本操作 xff0c 包括行列式 逆和秩 xff0c LU分解和QR分解 xff0c 以及范数等 其中LU分解和QR分解都是使用对角线上方或者下方的元素均为0的三角矩阵来进行计算 使用三角矩阵表示的线

随机推荐