List数据多重规则排序

来源:互联网 发布:淘宝南风小铺抄袭 编辑:程序博客网 时间:2024/06/07 00:21

List集合进行排序时,很多人会考虑 冒泡、快速等排序算法,但是对于多重排序规则的话,算法就不太适用了。其实java.util.Collections已经提供了 sort的排序方法,并且能自己实现其排序规则。

现在有个场景:我需要对一批优惠券进行排序, 优惠券有三个属性: 是否可用、券类型 、面额。   我需要将可用的、券类型最大的、面额最大的券排到最前面。

即优先按 是否可用排序,其次是券类型,再者就是面额。    

话不都说,看代码吧:

package com.test;import java.math.BigDecimal;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;/** * List多重规则排序测试类 * @author : shijing * 2017年5月3日上午11:00:51 */public class TestCompartor {    public static void main(String[] args) {        ArrayList<Coupon> persons = new ArrayList<Coupon>();        persons.add(new Coupon(13,0,new BigDecimal(40)));        persons.add(new Coupon(13,0,new BigDecimal(50)));        persons.add(new Coupon(13,0,new BigDecimal(45)));        persons.add(new Coupon(1,0,new BigDecimal(20)));        persons.add(new Coupon(13,1,new BigDecimal(30)));        persons.add(new Coupon(1,0,new BigDecimal(25)));        persons.add(new Coupon(11,0,new BigDecimal(50)));        persons.add(new Coupon(11,1,new BigDecimal(40)));        System.out.println("排序之前:");        for (int i = 0; i <persons.size(); i++) {            System.out.println(persons.get(i));        }        System.out.println();        Collections.sort(persons, new Comparator<Coupon>() {            //按可用升序,券类型降序,面额降序            public int compare(Coupon o1, Coupon o2) {                if (o1.valueAble.compareTo(o2.valueAble)==0){                if(o2.themeType.compareTo(o1.themeType)==0){                return o2.amount.compareTo(o1.amount)>0?1:-1;                }else{                return o2.themeType - o1.themeType;                }                }else{                    return o1.valueAble-o2.valueAble ;                }            }        });        System.out.println("排序后结果:");        for (int i = 0; i <persons.size(); i++) {            System.out.println(persons.get(i));        }    }            static class Coupon{        public Integer themeType;  //优惠券类型        public Integer valueAble; //可用  ,0 可用,1不可用        public BigDecimal amount;  //面额        @Override        public String toString() {            return "Person{" +                    "themeType=" + themeType +                    ", valueAble=" + valueAble +                    ", amount=" + amount +                    '}';        }public Coupon(Integer themeType, Integer valueAble, BigDecimal amount) {super();this.themeType = themeType;this.valueAble = valueAble;this.amount = amount;}            }}

至于封装工具类我就懒得弄了,有需要的自己封装吧。


1 0