Map/Reduce程序
1. Map
- public class MaxTemperatureMapper extends
- Mapper<LongWritable, Text, Text, IntWritable> {
- private static final int MISSIGN = 9999;
- @Override
- public void map(LongWritable key, Text value, org.apache.Hadoop.mapreduce.Mapper<LongWritable,Text,Text,IntWritable>.Context context) throws IOException ,InterruptedException {
- String line = value.toString();
- String year = line.substring(15, 19);
- int airTemperator = 0;
- if (line.charAt(87) == '+') {
- airTemperator = Integer.parseInt(line.substring(88, 92));
- } else {
- airTemperator = Integer.parseInt(line.substring(87, 92));
- }
- String quality = line.substring(92, 93);
- if (airTemperator < MISSIGN && quality.matches("[01459]")) {
- context.write(new Text(year), new IntWritable(airTemperator));
- }
- };
- }
2. Reduce
- public class MaxTemperatureReducer extends
- Reducer<Text, IntWritable, Text, IntWritable> {
- @Override
- public void reduce(Text key, Iterable<IntWritable> values, Context context)
- throws IOException, InterruptedException {
- int maxValue = Integer.MIN_VALUE;
- for (IntWritable value : values) {
- maxValue = Math.max(maxValue, value.get());
- }
- context.write(key, new IntWritable(maxValue));
- };
- }
3. Client
- public class MaxTemperature {
- public static void main(String[] args) throws Exception {
- if (args.length != 2) {
- System.out.println("Usage MaxTemperator <input path> <output path>");
- System.exit(-1);
- }
- Job job = new Job();
- job.setJarByClass(MaxTemperature.class);
- job.setMapperClass(MaxTemperatureMapper.class);
- job.setReducerClass(MaxTemperatureReducer.class);
- job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(IntWritable.class);
- FileInputFormat.addInputPath(job, new Path(args[0]));
- FileOutputFormat.setOutputPath(job, new Path(args[1]));
- System.exit(job.waitForCompletion(true) ? 0 : 1);
- }
- }
4. 运行
将上述程序达成jar包放到$HADOOP_CLASSPATH路径下。
然后执行 hadoop jar test.jar com.tx.weahter.MaxTemerature input/sample.txt output
