使用Java编写根据包含id,日期,手机号码、型号、操作系统字段的数据源生成分析2021年操作系统市场占比情况,要使用到MapReduce
时间: 2024-01-27 14:06:28 浏览: 27
好的,我理解你的问题了。使用Java编写MapReduce程序可以实现对数据源的分析,并生成2021年操作系统市场占比情况。下面是一个简单的思路:
1. Mapper阶段:将数据源中的每一行按照操作系统字段进行分组,即将同种操作系统的数据分为一组。同时,使用context.write()函数将该组数据的键值对作为Mapper阶段的输出结果,其中键为该操作系统的名称,值为该组数据的日期和手机号码。
2. Reducer阶段:对Mapper阶段的输出结果进行操作系统名称的聚合,即将同种操作系统的数据合并为一组。对于每一组数据,统计该操作系统的数量和占比,并将结果输出。
下面是一个简单的MapReduce程序实现:
```java
public class OSMarketShare {
public static class OSMarketMapper extends Mapper<LongWritable, Text, Text, Text> {
private Text os = new Text();
private Text data = new Text();
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] fields = line.split("\t");
os.set(fields[3]);
data.set(fields[1] + "," + fields[2]);
context.write(os, data);
}
}
public static class OSMarketReducer extends Reducer<Text, Text, Text, Text> {
private Text result = new Text();
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
int count = 0;
Map<String, Integer> dateCountMap = new HashMap<>();
for (Text val : values) {
count++;
String[] fields = val.toString().split(",");
if (dateCountMap.containsKey(fields[0])) {
dateCountMap.put(fields[0], dateCountMap.get(fields[0]) + 1);
} else {
dateCountMap.put(fields[0], 1);
}
}
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, Integer> entry : dateCountMap.entrySet()) {
sb.append(entry.getKey()).append(":").append(entry.getValue()).append(",");
}
double percentage = (double) count / 100;
result.set(count + "," + sb.toString() + percentage + "%");
context.write(key, result);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "OSMarketShare");
job.setJarByClass(OSMarketShare.class);
job.setMapperClass(OSMarketMapper.class);
job.setReducerClass(OSMarketReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
```
在使用MapReduce程序之前,需要将数据源按照HDFS格式存储,并将其作为程序的输入。在程序运行后,将会生成按照操作系统名称进行分组的结果,并统计每种操作系统的数量和占比。