大数据学习之十一——MapReduce代码实例:平面距离
Posted M_study
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了大数据学习之十一——MapReduce代码实例:平面距离相关的知识,希望对你有一定的参考价值。
***坐标距离***
场景描述:
已知一个单身美女的坐标,和一群单身帅哥的坐标,求离美女最近的帅哥
数据(空格分开x、y坐标):(10,12)(23,23)(20,20)(1,3)(23,7)
假设美女的坐标为(5,5)
代码实现:
public class distance2 {
static String INPUT_PATH="hdfs://master:9000/input/h.txt";
static String OUTPUT_PATH="hdfs://master:9000/output/distance2";
static class MyMapper extends Mapper<Object,Object,DoubleWritable,Text>{ //距离作为double类型,输出格式控制
DoubleWritable output_key=new DoubleWritable();
DoubleWritable output_value=new DoubleWritable();
DoubleWritable out_distance=new DoubleWritable();
Text record=new Text(); //输出格式的控制
protected void map(Object key, Object value, Context context) throws IOException, InterruptedException{
String[] tokens=value.toString().split(",",2); //按照,分隔开
output_key.set(Double.parseDouble(tokens[0])); //第一列给坐标x
output_value.set(Double.parseDouble(tokens[1])); //第二列给坐标y
double x1=output_key.get()-5; //平面距离公式
double y1=output_value.get()-5;
double x=output_key.get();
double y=output_value.get();
String rec="x:"+x+","+"y:"+y; //输出格式
out_distance.set(Math.sqrt(Math.pow(x1, 2)+Math.pow(y1, 2)));
record.set(rec);
context.write(out_distance, record);
}
}
static class MyReduce extends Reducer<DoubleWritable,Text,DoubleWritable,Text>{
DoubleWritable output_key=new DoubleWritable();
DoubleWritable output_value=new DoubleWritable();
protected void reduce(DoubleWritable key,Iterable<Text> values,Context context) throws IOException,InterruptedException{
while(values.iterator().hasNext()){ //循环写入
context.write(key,values.iterator().next());
}
}
}
public static void main(String[] args) throws Exception{
Path outputpath=new Path(OUTPUT_PATH);
Configuration conf=new Configuration();
Job job=Job.getInstance(conf);
FileInputFormat.setInputPaths(job, INPUT_PATH);
FileOutputFormat.setOutputPath(job,outputpath);
job.setMapperClass(MyMapper.class);
job.setReducerClass(MyReduce.class);
job.setOutputKeyClass(DoubleWritable.class);
job.setOutputValueClass(Text.class);
job.waitForCompletion(true);
}
}
以上是关于大数据学习之十一——MapReduce代码实例:平面距离的主要内容,如果未能解决你的问题,请参考以下文章