问题:选出蜀国中五虎将
原始数据如下:
序号 姓名 武力值 国家
1 刘备 68 蜀国
2 马超 90 蜀国
3 黄忠 91 蜀国
4 魏延 76 蜀国
5 姜维 92 蜀国
6 关羽 96 蜀国
7 严颜 78 蜀国
8 孟达 64 蜀国
9 张飞 88 蜀国
10马谡 76 蜀国
11 赵云 95 蜀国
12 法正 88 蜀国
预期结果如下:
6 关羽 96 蜀国
11 赵云 95 蜀国
5 姜维 92 蜀国
3 黄忠 91 蜀国
2 马超 90 蜀国
准备工作
新建一个数据文件
将其传到hdfs上
hdfs dfs -put ~/wujiang.txt input
我的文件是在/home/wang 下
在hadoop web上查看
分析
通过对武力值排序,得到按武力值排序的数据,输出前五行即可。
讲解
自定义比较函数MyWritable,实现按武力值排序,并让其他数据一直跟随着武力值,以便后面输出完整的数据
MyWritable.java
import org.apache.hadoop.io.WritableComparable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
public class MyWritable implements WritableComparable<MyWritable> {
private Integer num;
public String id;
public String name;
public String nation;
public MyWritable(Integer num, String a, String b, String c) {
this.num = num;
this.id=a;
this.name=b;
this.nation=c;
}
public MyWritable() {
}
@Override
public void write(DataOutput out) throws IOException {
o