单向好友的计算:
[mw_shl_code=java,true]static class UCFMapper extends Mapper<LongWritable, Text, Text, Text> {
@Override
protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context)
throws IOException, InterruptedException {
StringTokenizer valueLine = new StringTokenizer(value.toString());
// 获取每一行的自己
String owner = null;
if (valueLine.hasMoreTokens()) {
owner = valueLine.nextToken();
}
// 获取每一行人员的朋友 k-v:B-A,即A将B视为朋友,但B不一定这样认为
while (valueLine.hasMoreTokens()) {
context.write(new Text(valueLine.nextToken()), new Text(owner));
}
}
}
static class UCFComBine extends Reducer<Text, Text, Text, Text>{
protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context)
throws IOException, InterruptedException {
//翻转,计算任意两个人共同认同的朋友
Iterator<Text> ite = values.iterator();
Set<Object> set = new TreeSet<Object>();
while (ite.hasNext()) {
//提取出所有需要计算好友的人员
Text person = (Text) ite.next();
set.add(person.toString());
}
/*
* 计算两个人的共同好友,key即为两个人员的共同好友
*/
Object[] owners = set.toArray();
for (int i = 0; i < owners.length - 1; i++) {
for (int j = i + 1; j < owners.length; j++) {
String ownerKey = (String)owners+(String)owners[j];
context.write(new Text(ownerKey), key);
}
}
}
}
static class UCFReducer extends Reducer<Text, Text, Text, Text>{
@Override
protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context)
throws IOException, InterruptedException {
StringBuilder cf = new StringBuilder();
for (Text friend : values) {
cf.append(friend.toString());
}
context.write(key, new Text(cf.toString()));
}
}[/mw_shl_code]
输入:
[mw_shl_code=applescript,true]A B C D E
B C D
C D E[/mw_shl_code]
输出:
[mw_shl_code=applescript,true]AB CD
AC D
BC D
AC E[/mw_shl_code]
但还没有闹明白为什么AC的两个共同好友不合并
|