统计乘用车辆,商用车辆的数量销售和销售额分布

统计乘用车辆,商用车辆的数量销售和销售额分布

/**
* 根据汽车所属(个人,商用)来进行划分
* 计算乘用车辆,商用车辆各自的数量,以及各自所占的比重
*/
public static class CountMap extends Mapper{

	@Override
	public void map(LongWritable key, Text value,				
			Mapper.Context context)
			throws IOException, InterruptedException {
		
		String [] owns = value.toString().trim().split(" ");
		if(null != owns && owns.length > 10 && owns[10] != null) {
			if(owns[10].equals("非营运")) {
				context.write(new Text("乘用车辆"), new LongWritable(1));
			}else {
				context.write(new Text("商用车辆"), new LongWritable(1));
			}
		}			 
	};
}




/**
 * 统计乘用车辆和商用车辆的数量以及他们的总量
 */
public static class CountReduce extends Reducer {
	Map maps = new HashMap();
	//准备存放非营运的乘用车辆和营运的商用车辆的总和
	double all = 0;
	@Override
	public void reduce(Text key, Iterable values,Context context) throws IOException, InterruptedException {
		 Long sum = (long) 0;
		 for (LongWritable val : values) {
			sum += val.get();
		}
		 //求出车辆的总和
		 all += sum;
		 maps.put(key.toString(),sum);
	};

	protected  void cleanup(
			org.apache.hadoop.mapreduce.Reducer.Context context) throws IOException, InterruptedException {
		Set keySet = maps.keySet();
		//循环set集合中的乘用车辆和商用车辆的数量
		for (String str : keySet) {
			long value = maps.get(str);
			//用乘用车辆/总量  和  商用车辆/总量,求出各自的比例
			double percent = value/all;
			//输出的key为车辆类型,value的值为该车辆类型的占比
			context.write(new Text(str), new DoubleWritable(percent));
		}
	};
}

你可能感兴趣的:(hdfs)