-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordCount.java
More file actions
61 lines (49 loc) · 1.82 KB
/
WordCount.java
File metadata and controls
61 lines (49 loc) · 1.82 KB
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
import java.io.*;
import java.util.regex.Pattern;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.util.*;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class WordCount extends Configured implements Tool{
public static void main(String args[]) throws Exception {
int res = ToolRunner.run(new WordCount(), args);
System.exit(res);
}
public int run(String args[]) throws IOException, InterruptedException, ClassNotFoundException {
Job job = Job.getInstance(getConf(), "wordcount");
job.setJarByClass(this.getClass());
FileInputFormat.addInputPath(job, new Path("input.txt"));
FileOutputFormat.setOutputPath(job, new Path("output"));
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
return job.waitForCompletion(true)?0:1;
}
public static class Map extends Mapper<LongWritable, Text, Text, IntWritable>{
Pattern WORD_B = Pattern.compile("\\s*\\b\\s*");
public void map(LongWritable offset, Text lines, Context context) throws IOException, InterruptedException {
String line = lines.toString();
Text cw = new Text();
for(String w : WORD_B.split(line)){
if(w.isEmpty())
continue;
cw = new Text(w);
context.write(cw, new IntWritable(1));
}
}
}
public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {
@Override
public void reduce(Text word, Iterable<IntWritable> counts, Context context) throws IOException, InterruptedException{
int sum = 0;
for(IntWritable c : counts){
sum+=c.get();
}
context.write(word, new IntWritable(sum));
}
}
}