github地址:
https://github.com/crazyyanchao/SortedNmaePrice.git
输入文件:
Name.txt
shoes 1
router 2
settopbox 3
Price.txt
1 125
2 232
1 132
2 200
3 578
2 265
3 610
1 157
1 175
3 582
输出文件:
shoes 125
shoes 132
shoes 157
shoes 175
router 200
router 232
router 265
settopbox 578
settopbox 582
settopbox 610
源代码:
Homework.java
public class Homework {
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: homework");
System.exit(2);
}
//conf.setInt("mapred.task.timeout",100);
Job job = new Job(conf, "homework");
job.setInputFormatClass(TextInputFormat.class);
job.setJarByClass(Homework.class);
job.setMapperClass(mapper.class);
job.setReducerClass(reducer.class);
job.setMapOutputKeyClass(LongWritable.class);
job.setMapOutputValueClass(Text.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
job.setNumReduceTasks(1);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
mapper.java
public class mapper extends Mapper<Object,Text,LongWritable,Text> {
public void map(Object key,Text value,Context context)
throws IOException,InterruptedException{
String fileName = ((FileSplit)context.getInputSplit()).getPath().toString();
String valueString= value.toString();
String[] items=valueString.split(" ");
LongWritable outputKey = null;
Text outputValue=null;
if(fileName.contains("price")){
outputKey = new LongWritable(Long.valueOf(items[0]));
outputValue = new Text(items[1]);
}else{
outputKey = new LongWritable(Long.valueOf(items[1]));
outputValue = new Text("name" + items[0]);
}
context.write(outputKey,outputValue);
}
}
reduce.java
public class reducer extends Reducer<LongWritable,Text,Text,LongWritable> {
public void reduce(LongWritable key, Iterable<Text>values, Context context)
throws IOException, InterruptedException {
Text itemName = null;
TreeSet<LongWritable> queue = new TreeSet<LongWritable>();
for (Text val : values){
if(val.toString().startsWith("name")){
String realName = val.toString().substring(4);
itemName = new Text(realName);
}else{
LongWritable price = new LongWritable(Long.valueOf(val.toString()));//如果是价格则进入队列
queue.add(price);
}
}
for (LongWritable val : queue) {//遍历queue(这是一个耗费内存的解法)
context.write(itemName, val);
}
}
}