Comparable比较的重写方法

对于Map中的数据,按照ULStrcture中的util + rutil 进行排序。

1 通用版;用泛型

/* TODO Map的value值升序排序
     * @ param map 待排序的map
     * @ return returnMap 排序后的map
     * (特别说明:若value值降序排序,对应修改compare --> -compare)
     * */
    public <K, V  extends Comparable<? super V>> Map<K, V> sortDescend(Map<K, V> map) {
        List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
        list.sort(new Comparator<Map.Entry<K, V>>() {
            @Override
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                int compare = (o1.getValue()).compareTo(o2.getValue());
                return compare;  // return -compare(降序)
            }
        });

        Map<K, V> returnMap = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : list) {
            returnMap.put(entry.getKey(), entry.getValue());
        }
        return returnMap;
    }

重写compareTo方法

@Override
    public int compareTo(Object o2) {
        return Long.compare((((ULStructure)o2).utilSum() + ((ULStructure)o2).rutilSum()), this.rutilSum() + this.utilSum());
    }

2 自定义数据类型版

 public LinkedHashMap<Integer, ULStructure> sortDescend(LinkedHashMap<Integer, ULStructure> map) {
//    public <K, V extends Comparable<? super V>> Map<K, V> sortDescend(LinkedHashMap<K, V> map) {
        List<Map.Entry<Integer, ULStructure>> list = new ArrayList<>(map.entrySet());
        list.sort(new Comparator<Map.Entry<Integer, ULStructure>>() {
            @Override
            public int compare(Map.Entry<Integer, ULStructure> o1, Map.Entry<Integer, ULStructure> o2) {
                int compare = (o1.getValue()).compareTo(o2.getValue());
                return compare;  // return -compare(降序)
            }
        });

        LinkedHashMap<Integer, ULStructure> returnMap = new LinkedHashMap<Integer, ULStructure>();
        for (Map.Entry<Integer, ULStructure> entry : list) {
            returnMap.put(entry.getKey(), entry.getValue());
        }
        return returnMap;
    }

重写一下compareTo() 方法

 public int compareTo(ULStructure o2){
        return  Long.compare((o2.utilSum()+o2.rutilSum()),this.rutilSum()+this.utilSum());
    }

由于传入的参数不同,所以也会调用不同的compareTo()方法。

另外

定义一个数据类型,可以有不同的实现 (为了配合方法的调用)

Map<Integer, ULStructure> LUs = new LinkedHashMap<>();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值