BigData_A_A_03-YARN-资源管理和任务调度(2)共同好友(hadoop)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012848709/article/details/85238928

楔子

hadoop 统计共同好友

demo

思路是 两次遍历,按照 他俩是不是直接好友,如果是直接好友,输出 key(friendA + “:” + friendB) value(0)
如果 他俩是同一个人的好友 输出 key(friendA + “:” + friendB) value(0)
在根据 key分组求和,和就是他俩的共同好友个数
但是需要注意,还需要判断,如果他俩是直接好友,注意 他俩是不是其他人的间接好友

@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
	// 数据 格式是 tom hello hadoop cat(每个人和他的好友以空格分隔)
	String[] split = StringUtils.split(value.toString(), ' ');
	String user = split[0];

	for (int i = 1; i < split.length; i++) {
		mkey.set(friends(user, split[i]));
		mval.set(0);
		context.write(mkey, mval);
		System.out.println(mkey.toString() + mval);
		// 如果 A 和B 是直接 好友就输出 A:B 0
		for (int j = i + 1; j < split.length; j++) {
			mkey.set(friends(split[j], split[i]));
			mval.set(1);
			// 如果 A 和B 是间接 好友就输出 A:B 1;然后对key分组就和 和就是他们有多少共同好友
			context.write(mkey, mval);
			System.out.println(mkey.toString() + mval);
		}
	}

}

Reducer

@Override
protected void reduce(Text key, Iterable<IntWritable> val, Context context)
		throws IOException, InterruptedException {

	// 对 key 求和
	// hadoop:hello 1
	// hadoop:hello 0
	// hadoop:hello 1
	// hadoop:hello 1
	int sum = 0;
	// 是否是直接好友,因为存在这种情况,他俩是直接好友,但是他俩同时也是别人的间接好友,这种情况排除
	boolean flag = true;

	for (IntWritable v : val) {
		if (v.get() == 0) {
			flag = false;
		}
		sum += v.get();
	}
	// 如果不是直接好友输出
	if (flag) {
		rval.set(sum + "");
		context.write(key, rval);
	}
}

代码和数据位置 https://github.com/qianlicao51/hd/tree/master/src/main/java/cn/sxt/day1/hdfs/fof

猜你喜欢

转载自blog.csdn.net/u012848709/article/details/85238928