需求:求给定日期的最高温度
待处理数据内容:
201701082.6
201701066
2017020810
2017030816.33
2017060833.0
每一行的前8位是日期,从第8位往后是温度
代码
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
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;
/**
* 求最高温度
* @author lyd
*
* 数据:
*
* 201701082.6
* 201701066
* 2017020810
* 2017030816.33
* 2017060833.0
* 2017050126.6
* 2017050320.9
*
*/
public class HighTem {
public static class MyMapper extends Mapper<Object, Text, Text,Text>{
@Override
protected void map(Object key, Text value,Context context)
throws IOException, InterruptedException {
String line = value.toString();
String tmp = line.substring(8, line.length());
context.write(new Text(""), new Text(tmp));
/**
"" 201701082.6
"" 201701066
"" 2017020810
"" 2017030816.33
"" 2017060833.0
"" 2017050126.6
"" 2017050320.9
*/
}
}
/**
* 自定义reducer类
* @author lyd
*
*/
public static class MyReducer extends Reducer<Text, Text, Text, Text>{
@Override
protected void reduce(Text key, Iterable<Text> value,Context context)
throws IOException, InterruptedException {
/**
* "" list(2.6,6,10)
*/
double max = Double.MIN_VALUE;
//获取最大值
for (Text t : value) {
if(max < Double.parseDouble(t.toString())){
max = Double.parseDouble(t.toString());
}
}
context.write(new Text(max+""), new Text(""));
}
}
public static void main(String[] args) {
try {
//获取配置对象
Configuration conf = new Configuration();
//创建job
Job job = new Job(conf, "HighTemp");
//为job设置运行主类
job.setJarByClass(HighTem.class);
//设置map阶段的属性
job.setMapperClass(MyMapper.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
//设置reduce阶段的属性
job.setReducerClass(MyReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileOutputFormat.setOutputPath(job, new Path(args[1]));
//提交运行作业job 并打印信息
int isok = job.waitForCompletion(true)?0:1;
//退出job
System.exit(isok);
} catch (IOException | ClassNotFoundException | InterruptedException e) {
e.printStackTrace();
}
}
}