爱程序网

Java中的集合排序

来源: 阅读:

1. 定义排序

class ComparatorDefault implements Comparator {
        public int compare(Object arg0, Object arg1) {
            OrderDetailReturn.BidsEntity bid0 = (OrderDetailReturn.BidsEntity) arg0;
            OrderDetailReturn.BidsEntity bid1 = (OrderDetailReturn.BidsEntity) arg1;
            //按ID排序
            return bid0.getId() - bid1.getId();
        }
    }

    class ComparatorCredit implements Comparator {
        public int compare(Object arg0, Object arg1) {
            OrderDetailReturn.BidsEntity bid0 = (OrderDetailReturn.BidsEntity) arg0;
            OrderDetailReturn.BidsEntity bid1 = (OrderDetailReturn.BidsEntity) arg1;
            //按ID排序
            if (bid0.getBearer() == null || bid1.getBearer() == null) return 0;
            return bid0.getBearer().getScore() - bid1.getBearer().getScore();
        }
    }

    class ComparatorPrice implements Comparator {
        public int compare(Object arg0, Object arg1) {
            OrderDetailReturn.BidsEntity bid0 = (OrderDetailReturn.BidsEntity) arg0;
            OrderDetailReturn.BidsEntity bid1 = (OrderDetailReturn.BidsEntity) arg1;
            //按ID排序
            return bid0.getPrice() - bid1.getPrice();
        }
    }

2. 调用排序

if(bidList == null) return;
        Comparator comparator;
        if (style == 1) {
            comparator = new ComparatorCredit();
        } else if (style == 2) {
            comparator = new ComparatorPrice();
        } else {
            comparator = new ComparatorDefault();
        }
        Collections.sort(bidList, comparator);

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助