Code example by Apache Spark - wuyichen24/boost GitHub Wiki

This class will read the text file in the HDFS and counts the number of occurrences of each word in a given paragraph. The result will be exported to a new file in HDFS.

import java.util.*;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
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 WordCount1 {
    public static class WordCountMap extends Mapper<Object, Text, Text, IntWritable> {
        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
	    String line = value.toString();    // each value is one line in the paragraph
	    StringTokenizer tokenizer = new StringTokenizer(line);
            while (tokenizer.hasMoreTokens()) {
	        String nextToken = tokenizer.nextToken();
		context.write(new Text(nextToken), new IntWritable(1));

    public static class WordCountReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
        public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
	    int sum = 0;
	    for (IntWritable val : values) {
	        sum += val.get();
	    context.write(key, new IntWritable(sum));

    public static void main(String[] args) throws Exception {
        Job job = Job.getInstance(new Configuration(), "wordcount");


        FileInputFormat.setInputPaths(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

	System.exit(job.waitForCompletion(true) ? 0 : 1);