目录
- 1.需求:离线计算两两之间的共同好友
- 2.思路:分两步
1.需求:离线计算两两之间的共同好友
2.思路:分两步
第一步:计算<友,[人,人,..]>
static class sharedFriendsStepOneMapper extends Mapper<LongWritable, Text, Text, Text>{
String person = "";
String friends = "";
Text _friend = new Text();
Text _person = new Text();
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] personAndFriends = line.split(":");
person = personAndFriends[0];
friends = personAndFriends[1];
for(String friend : friends.split(",")){
_friend.set(friend);
_person.set(person);
context.write(_friend, _person);
}
}
}
static class sharedFriendsStepOneReducer extends Reducer <Text, Text,Text, Text>{
@Override
protected void reduce(Text friend, Iterable<Text> persons, Context context) throws IOException, InterruptedException {
Text _persons = new Text();
StringBuffer sb = new StringBuffer();
for(Text person : persons){
sb.append(person);
sb.append(",");
}
_persons.set(sb.toString());
context.write(friend, _persons);
}
}
第二步:计算<人-人,[友,友,..]>
static class sharedFriendsStepTwoMapper extends Mapper<LongWritable,Text,Text,Text>{
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] friendAndPersons = line.split("\t");
String friend = friendAndPersons[0];
String[] persons = friendAndPersons[1].split(",");
Arrays.sort(persons);
for(int i = 0; i<persons.length-1; i++){
for(int j = i+1; j<persons.length; j++){
context.write(new Text(persons[i] + "-" + persons[j]), new Text(friend));
}
}
}
}
static class sharedFriendsStepTwoReducer extends Reducer<Text,Text,Text,Text>{
@Override
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
StringBuffer sb = new StringBuffer();
for(Text value : values){
sb.append(value).append(",");
}
context.write(key,new Text(sb.toString()));
}
}