下面列举代码:
package climate;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class MaxTemeratureMapper extends Mapper{
@Override
protected void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String line = value.toString();
if(line.length() < 14){
System.out.println("less then 14");
}else{
String year = line.substring(10, 14);
Text tYear = new Text(year); //
int temperature = Integer.parseInt(line.substring(17, 22));
IntWritable iTemperature = new IntWritable(temperature);
context.write(tYear, iTemperature);
}
}
}
package climate;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class MaxTemperatureReduce extends Reducer{
@Override
protected void reduce(Text key, Iterable values,Context context)
throws IOException, InterruptedException {
int maxValue = Integer.MIN_VALUE;
IntWritable result = new IntWritable();
for(IntWritable var : values){
maxValue = Math.max(maxValue, var.get());
}
result.set(maxValue);
context.write(key, result);
}
}
package climate;
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.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class Climate {
public static void main(String [] args) throws Exception{
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("Usage: climate in out directory");
System.exit(2);
}
long startTime = System.currentTimeMillis();
Job job = new Job(conf, "climate");
job.setJarByClass(Climate.class);
job.setMapperClass(MaxTemeratureMapper.class);
job.setCombinerClass(MaxTemperatureReduce.class);
job.setReducerClass(MaxTemperatureReduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
if(job.waitForCompletion(true))
{
System.out.println("dealing time:"+ (System.currentTimeMillis() - startTime) + "ms");
}
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}