idea 虚拟机 WordCount单词计数

设置文件夹

idea 虚拟机 WordCount单词计数_第1张图片

WordCountMapper代码

package com.mapreduce;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class WordCountMapper extends Mapper {
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String line=value.toString();
        String[] words= StringUtils.split(line," ");
        for (String word:words){
            context.write(new Text(word),new LongWritable(1));

        }
    }
}

WordCountReducer代码

package com.mapreduce;


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

import java.io.IOException;


public class WordCountReducer extends Reducer {
    @Override
    protected void reduce(Text key, Iterable values, Context context)
            throws IOException, InterruptedException {
        long count=0;
        for(LongWritable value:values){
            count=count+value.get();
        }
        context.write(key,new LongWritable(count));
    }
}

WordCountRunner代码

package com.mapreduce;


import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
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 java.io.IOException;

public class WordCountRunner {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration configuration=new Configuration();
        Job wcjop=Job.getInstance(configuration);

        wcjop.setMapperClass(WordCountMapper.class);
        wcjop.setReducerClass(WordCountReducer.class);

        wcjop.setJarByClass(WordCountRunner.class);

        wcjop.setMapOutputKeyClass(Text.class);
        wcjop.setMapOutputValueClass(LongWritable.class);

        wcjop.setOutputKeyClass(Text.class);
        wcjop.setOutputValueClass(LongWritable.class);

        FileInputFormat.setInputPaths(wcjop,new Path("hdfs://192.168.2.100:9000/wc/"));
        FileOutputFormat.setOutputPath(wcjop,new Path("hdfs://192.168.2.100:9000/out/"));
        wcjop.waitForCompletion(true);
    }
}

idea 虚拟机 WordCount单词计数_第2张图片

 hadoop jar hdfs3.jar com.mapreduce.WordCountRunner

结果
idea 虚拟机 WordCount单词计数_第3张图片

你可能感兴趣的:(idea 虚拟机 WordCount单词计数)