WordCount编程

//MyMap方法一
package s27;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;
import java.util.StringTokenizer;

public class MyMap extends Mapper<LongWritable,Text,Text,IntWritable> {

@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
    //super.map(key, value, context);

    StringTokenizer st = new StringTokenizer(value.toString());
    Text result = new Text();
    IntWritable one = new IntWritable(1);

    while (st.hasMoreTokens()){
        String word = st.nextToken();
        result.set(word);
        context.write(result,one);
    }
}

}

//MyMap方法二
package s27;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;
import java.util.StringTokenizer;

public class MyMap extends Mapper<LongWritable,Text,Text,IntWritable>{

@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

// StringTokenizer st=new StringTokenizer(value.toString());
// Text result=new Text();
// IntWritable one=new IntWritable(1);
//
// while(st.hasMoreTokens()){
// String word=st.nextToken();
// result.set(word);
// context.write(result,one);
Text result=new Text();
IntWritable one=new IntWritable(1);

    String line=value.toString();
    String[] words = line.split(" ");

    for(String w:words){
        result.set(w);
        context.write(result,one);
    }
}

}

package s27;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

public class MyRed extends Reducer<Text,IntWritable,Text,IntWritable> {

@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
    //super.reduce(key, values, context);
    int sum = 0;
    for(IntWritable i:values){
        sum += i.get();
    }
    context.write(key,new IntWritable(sum));

}

}

posted @ 2020-10-25 20:50  bky000001  阅读(90)  评论(0)    收藏  举报