题目:
a+b per line 描述 有时候你会遇到这样的问题:你有一个表格,给出了每个人在十二月,一月和二月的收入。表格如下: name Dec Jan($) CM 200 314 LY 2000 332 QQM 6000 333 ZYM 5000 333 BP 30 12 你需要知道每个人这三个月的收入总和,那么你就需要将表格中一行代表收入的数字相加.下面请编写程序解决这个问题。 输入 输入只包含一个文件,文件中有一个表格,它的结构如下: 1 200 314 2 2000 332 3 6000 333 4 5000 333 5 30 12 其中每行最前面的数字是行标 输出 输出是一个文本文件,每一行第一个数字式行标,第二个数字是输入文件中每一行除行标外数字的和。如下: 1 514 2 2332 3 6333 4 5333 5 42 输入样例 input: 1 200 314 2 2000 332 3 6000 333 4 6000 333 5 5000 333 6 30 12 输出样例: 1 514 2 2332 3 6333 4 6333 5 5333 6 42 注意: 1 输入文件和输出文件都只有一个; 2 输入和输出文件每行的第一个数字都是行标; 3 每个数据都是正整数或者零.。解答:
package com.wyan;
import java.io.IOException;
import java.util.StringTokenizer;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.Mapper; 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.GenericOptionsParser;public class CountPerline {
public static class TokenizerMapper
extends Mapper<Object, Text, Text, IntWritable>{ private Text word = new Text(); public void map(Object key, Text value, Context context ) throws IOException, InterruptedException { StringTokenizer itr = new StringTokenizer(value.toString()); if(itr.hasMoreTokens()) word.set(itr.nextToken()); while (itr.hasMoreTokens()) { IntWritable data= new IntWritable( Integer.parseInt( itr.nextToken() ) ); context.write(word, data); } } } public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> { private IntWritable result = new IntWritable();public void reduce(Text key, Iterable<IntWritable> values,
Context context ) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); context.write(key, result); } }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: wordcount <in> <out>"); System.exit(2); } Job job = new Job(conf, "word count"); job.setJarByClass(CountPerline.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(otherArgs[0])); FileOutputFormat.setOutputPath(job, new Path(otherArgs[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }