Skip to content

Instantly share code, notes, and snippets.

@soren
Last active December 26, 2015 21:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soren/7213453 to your computer and use it in GitHub Desktop.
Save soren/7213453 to your computer and use it in GitHub Desktop.
A Hadoop Word Count example using my own map and reduce classes. Tested with Java 1.6 and Hadoop 1.0.4.
import java.io.IOException;
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;
public class MyWordCount {
public static class MyWordCountMapper extends Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
for (String str : value.toString().toLowerCase().split("[\\W\\s]+")) {
word.set(str);
context.write(word, one);
}
}
}
public static class MyWordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int total = 0;
for (IntWritable val : values) total += val.get();
context.write(key, new IntWritable(total));
}
}
public static void main(String[] args) throws Exception {
Job job = new Job(new Configuration(), "My Word Count");
job.setJarByClass(MyWordCount.class);
job.setMapperClass(MyWordCountMapper.class);
job.setCombinerClass(MyWordCountReducer.class);
job.setReducerClass(MyWordCountReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment