基于eclipse mapreduce hadoop的天气统计代码
时间: 2023-07-11 08:33:00 浏览: 92
好的,下面是一个简单的基于Eclipse、MapReduce和Hadoop的天气统计代码示例,供您参考:
1. Mapper类
```java
public class WeatherMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
private Text outputKey = new Text();
private IntWritable outputValue = new IntWritable();
@Override
protected void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String line = value.toString();
String[] fields = line.split(",");
// 获取日期和温度
String date = fields[0];
int temperature = Integer.parseInt(fields[1]);
// 将日期作为MapReduce的输出key,温度作为输出value
outputKey.set(date);
outputValue.set(temperature);
context.write(outputKey, outputValue);
}
}
```
2. Reducer类
```java
public class WeatherReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable outputValue = new IntWritable();
@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context context)
throws IOException, InterruptedException {
int sum = 0;
int count = 0;
for (IntWritable value : values) {
sum += value.get();
count++;
}
// 计算平均温度并输出
int avg = sum / count;
outputValue.set(avg);
context.write(key, outputValue);
}
}
```
3. Driver类
```java
public class WeatherDriver {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf);
job.setJarByClass(WeatherDriver.class);
job.setMapperClass(WeatherMapper.class);
job.setReducerClass(WeatherReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
boolean result = job.waitForCompletion(true);
System.exit(result ? 0 : 1);
}
}
```
以上是一个简单的示例代码,根据实际情况和需求进行修改和完善。在运行代码前,需要将代码打包成jar包并上传到Hadoop集群进行运行。
阅读全文