您好,登錄后才能下訂單哦!
這篇文章主要介紹Hadoop如何實現求平均成績,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
//思路根據hadoop原理歸并相同人名,以人名為key,以各科成績為value容器元素,計算容器值的和,除以科目數。 public class AverageScore { 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 line = new StringTokenizer(value.toString(),"\n"); while (line.hasMoreElements()) { //按照空格分割 StringTokenizer lineBlock = new StringTokenizer(line.nextToken()); String stuName = lineBlock.nextToken(); int stuScore = Integer.parseInt(lineBlock.nextToken()); word.set(stuName); context.write(word, new IntWritable(stuScore)); } } }
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; int count =0; while(values.iterator().hasNext()){ sum+=values.iterator().next().get(); count++; } int average = sum/count; result.set(average); 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(AverageScore.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); } }
以上是“Hadoop如何實現求平均成績”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。