-
Notifications
You must be signed in to change notification settings - Fork 0
/
WordCount.java
85 lines (70 loc) · 2.43 KB
/
WordCount.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import java.util.StringTokenizer;
import java.io.IOException;
public class WordCount
{
// Mapper class-> output -> string,int
public static class WordMapper extends Mapper<Object,Text,Text,IntWritable>
{
Text word=new Text(); //Output key value
public void map(Object key, Text value, Context context) throws IOException,InterruptedException
{
StringTokenizer s=new StringTokenizer(value.toString());
while(s.hasMoreTokens())
{
String token=s.nextToken();
word.set(token);
context.write(word, new IntWritable(1));
}
}
}
//Reducer class -> string, int
public static class WordReducer extends Reducer<Text,IntWritable,Text,IntWritable>
{
public void reduce(Text key,Iterable<IntWritable> values,Context context) throws IOException, InterruptedException
{
IntWritable addition=new IntWritable();
int sum=0;
for(IntWritable num : values){
sum=sum+num.get();
}
addition.set(sum);
context.write(key,addition);
}
}
public static void main(String args[]) throws Exception
{
//create the object of Configuration class
Configuration conf=new Configuration();
//create the object of Job calss
Job job=new Job(conf,"WordCount");
//set the data type of output key
job.setOutputKeyClass(Text.class);
//set the data type of output value
job.setOutputValueClass(IntWritable.class);
//set the data format of output
job.setOutputFormatClass(TextOutputFormat.class);
//set the data format of input
job.setInputFormatClass(TextInputFormat.class);
//set the name of mapper class
job.setMapperClass(WordMapper.class);
//set the name of reducer class
job.setReducerClass(WordReducer.class);
//set the input file path from 0th argument
FileInputFormat.addInputPath(job,new Path(args[0]));
//set the output file path from 0th argument
FileOutputFormat.setOutputPath(job,new Path(args[1]));
//Execute the job and wait for completion
job.waitForCompletion(true);
}
}