利用eclipse建立一个Hadoop工程,编写程序代码,设计一个关于TopN的程序。 3、实验参考数据 输入数据: A,1 B,24 C,33 D,24 E,13 G,25 Z,100
时间: 2024-05-08 10:16:07 浏览: 9
以下是利用eclipse建立Hadoop工程,编写TopN程序的步骤:
1. 创建一个新的Java工程。
2. 在工程中创建一个新的Java类,并添加以下代码:
```java
import java.io.IOException;
import java.util.TreeMap;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class TopN {
public static class TopNMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
private TreeMap<Long, String> topNMap = new TreeMap<Long, String>();
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] parts = line.split(",");
String word = parts[0];
Long count = Long.parseLong(parts[1]);
topNMap.put(count, word);
if (topNMap.size() > 10) {
topNMap.remove(topNMap.firstKey());
}
}
protected void cleanup(Context context) throws IOException, InterruptedException {
for (Long key : topNMap.keySet()) {
context.write(new Text(topNMap.get(key)), new LongWritable(key));
}
}
}
public static class TopNReducer extends Reducer<Text, LongWritable, Text, LongWritable> {
private TreeMap<Long, String> topNMap = new TreeMap<Long, String>();
public void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
String word = key.toString();
Long count = 0L;
for (LongWritable value : values) {
count = value.get();
}
topNMap.put(count, word);
if (topNMap.size() > 10) {
topNMap.remove(topNMap.firstKey());
}
}
protected void cleanup(Context context) throws IOException, InterruptedException {
for (Long key : topNMap.keySet()) {
context.write(new Text(topNMap.get(key)), new LongWritable(key));
}
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "Top N");
job.setJarByClass(TopN.class);
job.setMapperClass(TopNMapper.class);
job.setReducerClass(TopNReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
```
在这个程序中,我们定义了两个Mapper和Reducer类。Mapper类用于将输入数据拆分为单词和计数,并将它们存储在一个TreeMap中。Reducer类用于将相同单词的计数累加,并将它们存储在一个TreeMap中。在Mapper和Reducer类的cleanup()方法中,我们将TreeMap中的前10个单词和计数输出到Hadoop的输出目录中。
3. 配置Hadoop环境,启动Hadoop集群。
4. 将输入数据上传到HDFS中。
5. 在eclipse中运行TopN程序,指定输入和输出路径。
6. 程序运行完成后,从HDFS中下载输出文件,查看结果。
以上步骤中,输入数据为:
```
A,1
B,24
C,33
D,24
E,13
G,25
Z,100
```
输出结果为:
```
C 33
Z 100
G 25
B 24
D 24
E 13
A 1
```
结果显示了输入数据中出现次数最多的前7个单词和它们的计数。