100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Writing a MapReduce Job in Java

A practical walkthrough of assembling a Driver, Mapper, and Reducer into a runnable Java MapReduce job, from configuration to cluster execution.

MapReduceIntermediate11 min readJul 10, 2026
Analogies

Anatomy of a Java MapReduce Job

A complete Hadoop MapReduce job in Java is made of three cooperating pieces: a Driver class containing the main() method that configures and submits the job, a Mapper subclass implementing map(), and a Reducer subclass implementing reduce() (with an optional Combiner, often the same class as the Reducer for associative operations). The Driver constructs a Configuration and a Job object bound to it, wires in the mapper, reducer, combiner, and input/output paths, then calls job.waitForCompletion(true) to submit the job to the cluster (or LocalJobRunner in local mode) and block until it finishes, returning a boolean success flag the driver typically uses to set the process exit code.

🏏

Cricket analogy: Running a franchise involves three cooperating roles: the team owner who sets budget and strategy (Driver), the head coach who trains individual batting technique (Mapper), and the strategist who reviews match footage to refine overall game plans (Reducer), each with a clear separation of duties.

Implementing Mapper and Reducer Classes

Both Mapper<KEYIN, VALUEIN, KEYOUT, VALUEOUT> and Reducer<KEYIN, VALUEIN, KEYOUT, VALUEOUT> are generic classes parameterized by their input and output key/value types, and every type used must implement Hadoop's Writable interface (for values) or WritableComparable (for keys, since keys must be sortable) — common built-ins include Text, IntWritable, LongWritable, DoubleWritable, and NullWritable. Critically, the reducer's KEYIN/VALUEIN types must exactly match the mapper's KEYOUT/VALUEOUT types, since that's the intermediate contract the framework enforces at job submission time; a mismatch, like a mapper emitting IntWritable values while the reducer expects Text, causes a runtime ClassCastException rather than a compile-time error, because the framework can't fully verify generic type parameters across the shuffle boundary.

🏏

Cricket analogy: A bowling coach and a batting coach must agree on exactly which drill format the fielding notes use, since a mismatch, like the bowling coach logging speeds in km/h while the batting coach's system expects mph, only surfaces as a broken report at review time, not before training starts, mirroring the mapper/reducer type contract failing at runtime.

Configuring and Submitting the Job

A typical driver builds the job with Job.getInstance(conf, "job name"), calls setJarByClass() so Hadoop can locate the job's JAR on the classpath, sets setMapperClass(), setCombinerClass() (optional), and setReducerClass(), declares setOutputKeyClass() and setOutputValueClass() for the final output types, optionally overrides setMapOutputKeyClass()/setMapOutputValueClass() when intermediate types differ from final output types, and finally wires FileInputFormat.addInputPath() and FileOutputFormat.setOutputPath() before calling waitForCompletion(). Hadoop refuses to run if the output path already exists, as a safety measure against accidentally overwriting a previous job's results, so driver code (or the shell script invoking it) commonly deletes or timestamps the output directory before resubmitting during iterative development.

🏏

Cricket analogy: Before a match, the umpires check the pitch report, confirm both playing XIs, and verify the toss result before play can begin — skipping any of these checks means the match can't officially start, similar to how a Job object needs its mapper, reducer, and I/O paths all configured before waitForCompletion() can run.

java
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.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class WordCountDriver extends Configured implements Tool {

    @Override
    public int run(String[] args) throws Exception {
        if (args.length != 2) {
            System.err.println("Usage: WordCountDriver <input> <output>");
            return -1;
        }

        Configuration conf = getConf();
        Job job = Job.getInstance(conf, "word count");
        job.setJarByClass(WordCountDriver.class);

        job.setMapperClass(WordCountMapper.class);
        job.setCombinerClass(WordCountReducer.class);
        job.setReducerClass(WordCountReducer.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

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

        return job.waitForCompletion(true) ? 0 : 1;
    }

    public static void main(String[] args) throws Exception {
        int exitCode = ToolRunner.run(new Configuration(), new WordCountDriver(), args);
        System.exit(exitCode);
    }
}

Extending Configured and implementing Tool, then launching via ToolRunner.run(), automatically enables Hadoop's GenericOptionsParser, which parses standard cluster options like -D mapreduce.job.reduces=10, -files, -libjars, and -archives from the command line before your own args[] array is populated — writing a plain main() without ToolRunner silently loses this capability.

Testing and Running on a Cluster

Before submitting to a real cluster, it's standard practice to run the job in local mode (mapreduce.framework.name=local, the default when no cluster config is present) against a small sample dataset, or to use a unit testing library like MRUnit or plain JUnit tests against the Mapper/Reducer classes directly by calling map()/reduce() with mocked Context objects, catching logic bugs cheaply before burning cluster time. Once packaged into a JAR (typically with dependencies shaded in via Maven's shade plugin or a similar mechanism), the job is submitted with hadoop jar mycode.jar com.example.WordCountDriver /input/path /output/path, and progress and errors can be inspected afterward with yarn logs -applicationId <id> or through the YARN ResourceManager web UI.

🏏

Cricket analogy: A batsman practices against a bowling machine in the nets on a small set of deliveries before facing live bowling in a real match, catching technique flaws cheaply before it matters, mirroring local-mode testing before a full cluster run.

A very common runtime error is forgetting to call setMapOutputKeyClass()/setMapOutputValueClass() when the mapper's intermediate output types differ from the final job output types set via setOutputKeyClass()/setOutputValueClass() — Hadoop assumes intermediate and final types match unless told otherwise, and the mismatch surfaces as a ClassCastException deep in the shuffle, often with a confusing stack trace far from the actual misconfiguration.

  • A Java MapReduce job is composed of a Driver, a Mapper subclass, and a Reducer subclass, with an optional Combiner.
  • All key and value types must implement Writable (values) or WritableComparable (keys) such as Text or IntWritable.
  • The reducer's input types must exactly match the mapper's output types, or a runtime ClassCastException occurs.
  • Job.getInstance, setJarByClass, setMapperClass, setReducerClass, and I/O paths must all be configured before submission.
  • Extending Tool and using ToolRunner enables standard command-line cluster options via GenericOptionsParser.
  • Local-mode runs and MRUnit/JUnit tests catch logic bugs cheaply before submitting to a real cluster with hadoop jar.
  • Forgetting setMapOutputKeyClass/setMapOutputValueClass when intermediate types differ from final types is a common bug.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#HadoopStudyNotes#WritingAMapReduceJobInJava#Writing#MapReduce#Job#Java#StudyNotes#SkillVeris#ExamPrep

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse