TopN全排序 RawComparator WritableComparable

一,TopN全排序的实现有两种方式
1.对象实现WritableComparable接口
Bean类

public class FlowBean implements WritableComparable<FlowBean> {

    private long upFlow;
    private long downFlow;
    private long sumFlow;

    public FlowBean() {
        super();
    }

    @Override
    public int compareTo(FlowBean flowBean) {
//        int result = 0;
//        if (this.sumFlow>flowBean.sumFlow){
//            result = -1;
//        }else if (this.sumFlow<flowBean.sumFlow){
//            result = 1;
//        }
        int result = -Long.compare(this.sumFlow,flowBean.sumFlow);
        return result;
    }
}

2.不实现WritableComparable接口,使用自定义的类,实现RawComparator
MyComparator类

public class RawComparatorTest implements RawComparator<FlowBean> {
	// 注意,不new会报空指针异常
    private  FlowBean o1 = new FlowBean();
    private  FlowBean o2 = new FlowBean();
    private  DataInputBuffer buffer = new DataInputBuffer();


    @Override
    public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
        try {
            buffer.reset(b1, s1, l1);                   // parse key1
            o1.readFields(buffer);

            buffer.reset(b2, s2, l2);                   // parse key2
            o2.readFields(buffer);

            buffer.reset(null, 0, 0);                   // clean up reference
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return compare(o1, o2);
    }

    @Override
    public int compareTo(FlowBean flowBean) {
//        int result = 0;
//        if (this.sumFlow>flowBean.sumFlow){
//            result = -1;
//        }else if (this.sumFlow<flowBean.sumFlow){
//            result = 1;
//        }

		//  idea会自动帮合并的
        int result = -Long.compare(this.sumFlow,flowBean.sumFlow);
        return result;
        
        // 注意:bean里面的sumFlow要定义成包装类,Long,才有以下方法
        // return -o1.getSumFlow().compareTo(o2.getSumFlow());
    }

Driver类:

// 里面设置自定义的比较器(在Mapper阶段就拍好序的)
job.setSortComparatorClass(RawComparatorTest.class);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值