shjhd1jp1
import com._51doit.mr.join.Join;
import com._51doit.mr.line.LineDemo;
import com._51doit.pojo.JoinBean;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.zookeeper.txn.Txn;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Friend1 {
// Mapper后面的括号中跟的是数据类型。
//前两个数据类型是读取数据时的格式,也就是<LongWritable,Text>
//后两个数据类型输出的格式,也就是map阶段得到的键值对<key,value>的对应的数据类型。
static class Friend1Mapper extends Mapper<LongWritable , Text , Text , Text>{
Text k = new Text() ;
Text v = new Text() ;
@Override
//key和value前面的数据类型,就是上一句代码Mapper后面<>里面的前两个数据类型
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();//获取Mapper端的输入值
String[] split = line.split(":");//以冒号拆分行文本数据,冒号左边是用户,右边是好友
String id = split[0];//获取输入值中的用户名称
//将冒号右边的字符串以逗号拆分,放入数组
String[] fs = split[1].split(",");//获取输入值中的好友列表
v.set(id);
for (String f : fs) {
k.set(f);
context.write(k,v);
}
}
}
static class Friend1Reducer extends Reducer<Text , Text ,Text,Text>{
@Override
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
List<String> list = new ArrayList<String>() ;
for (Text value : values) { // B C D F G H I K O
String f = value.toString();
list.add(f) ;
}
// 排序
Collections.sort(list);
for(int i=0 ; i < list.size()-1;i++){ // 0
for(int j=i+1 ; j<list.size();j++){ // 1 2 3 4 5 6
String pre = list.get(i); // B C
String post = list.get(j);// D F G H I K O
context.write(new Text(pre+"和"+post+"共同好友是:"),key);// key ==F
}
}
}
}
public static void main(String[] args) throws Exception {
Logger.getLogger("org").setLevel(Level.ERROR);
Configuration conf = new Configuration();
// 参数2 job的名字
Job job = Job.getInstance(conf, new LineDemo().getClass().getSimpleName());
job.setMapperClass(Friend1Mapper.class);
job.setReducerClass(Friend1Reducer.class);
// 设置map阶段的输出类型
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Text.class);
// 最终结果的数据类型
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
// job.setNumReduceTasks(2); //启动3个reduce任务
// 待处理数据的路径
FileInputFormat.setInputPaths(job, new Path("D:\\data\\friend\\input"));
FileOutputFormat.setOutputPath(job, new Path("D:\\data\\friend\\out2"));
job.waitForCompletion(true);
}
}