source: proiecte/HadoopA51/src/WordCount.java @ 166

Last change on this file since 166 was 166, checked in by (none), 14 years ago

HadoopA51: imported git repository from github

File size: 2.3 KB
Line 
1package org.apache.hadoop.examples;
2
3import java.io.IOException;
4import java.util.StringTokenizer;
5
6import org.apache.hadoop.conf.Configuration;
7import org.apache.hadoop.fs.Path;
8import org.apache.hadoop.io.IntWritable;
9import org.apache.hadoop.io.Text;
10import org.apache.hadoop.mapreduce.Job;
11import org.apache.hadoop.mapreduce.Mapper;
12import org.apache.hadoop.mapreduce.Reducer;
13import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
14import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
15import org.apache.hadoop.util.GenericOptionsParser;
16
17public class WordCount {
18
19  public static class TokenizerMapper 
20       extends Mapper<Object, Text, Text, IntWritable>{
21   
22    private final static IntWritable one = new IntWritable(1);
23    private Text word = new Text();
24     
25    public void map(Object key, Text value, Context context
26                    ) throws IOException, InterruptedException {
27      StringTokenizer itr = new StringTokenizer(value.toString());
28      while (itr.hasMoreTokens()) {
29        word.set(itr.nextToken());
30        context.write(word, one);
31      }
32    }
33  }
34 
35  public static class IntSumReducer 
36       extends Reducer<Text,IntWritable,Text,IntWritable> {
37    private IntWritable result = new IntWritable();
38
39    public void reduce(Text key, Iterable<IntWritable> values, 
40                       Context context
41                       ) throws IOException, InterruptedException {
42      int sum = 0;
43      for (IntWritable val : values) {
44        sum += val.get();
45      }
46      result.set(sum);
47      context.write(key, result);
48    }
49  }
50
51  public static void main(String[] args) throws Exception {
52    Configuration conf = new Configuration();
53    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
54    if (otherArgs.length != 2) {
55      System.err.println("Usage: wordcount <in> <out>");
56      System.exit(2);
57    }
58    Job job = new Job(conf, "word count");
59    job.setJarByClass(WordCount.class);
60    job.setMapperClass(TokenizerMapper.class);
61    job.setCombinerClass(IntSumReducer.class);
62    job.setReducerClass(IntSumReducer.class);
63    job.setOutputKeyClass(Text.class);
64    job.setOutputValueClass(IntWritable.class);
65    FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
66    FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
67    System.exit(job.waitForCompletion(true) ? 0 : 1);
68  }
69}
Note: See TracBrowser for help on using the repository browser.