集合自定义字段排序

Collections是java.util下的一个工具类,而sort方法是用来对数据进行排序操作;

  public static <T> void sort(List<T> list, Comparator<? super T> c) {
        list.sort(c);
    }

因业务需要对数据重新组合,并排序数据;因此需自定义排序规则。

/**
 * 排序测试
 * @Author Cheng.Wei
 * @Date  2018/06/24 22:16
 */
public class SortBate {
    public static void main(String[] args) {
        List<User> users = new ArrayList<User>(){{
            add(new User(20,"张三", 30));
            add(new User(28,"李四", 33));
            add(new User(22,"王五", 29));
        }};
        ListSort.sort(users, "id", ListSort.SortType.DESC);
        System.out.println("===========按【ID】倒叙===========");
        users.forEach(p-> System.out.println(p));
        System.out.println("===========按【ID】正序===========");
        ListSort.sort(users, "id", ListSort.SortType.ASC);
        users.forEach(p-> System.out.println(p));
        ListSort.sort(users, "age", ListSort.SortType.DESC);
        System.out.println("===========按【年龄】倒叙==========");
        users.forEach(p-> System.out.println(p));
        System.out.println("===========按【年龄】正序==========");
        ListSort.sort(users, "age", ListSort.SortType.ASC);
        users.forEach(p-> System.out.println(p));
    }
}
/**
 * 人员
 * @Author Cheng.Wei
 * @Date  2018/06/24 22:13
 */
public class User {
    private int id;
    private String name;
    private int age;
    //省略getter settet
}
输出结果:
===========按【ID】倒叙===========
User{id=28, name='李四', age=33}
User{id=22, name='王五', age=29}
User{id=20, name='张三', age=30}
===========按【ID】正序===========
User{id=20, name='张三', age=30}
User{id=22, name='王五', age=29}
User{id=28, name='李四', age=33}
===========按【年龄】倒叙==========
User{id=28, name='李四', age=33}
User{id=20, name='张三', age=30}
User{id=22, name='王五', age=29}
===========按【年龄】正序==========
User{id=22, name='王五', age=29}
User{id=20, name='张三', age=30}
User{id=28, name='李四', age=33}

排序工具:

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * 集合排序
 *         支持数字、日期、字符串
 * @Author Cheng.Wei
 * @Date 2018/06/24 21:54
 */
public class ListSort<T> {
    /**
     *  指定字段排序
     * @param list 集合
     * @param fieldLabel  字段
     * @param sortType 排序方式
     * @param <T>
     */
    public static <T> void sort(List<T> list, final String fieldLabel, SortType sortType){
        Collections.sort(list, new Comparator<T>() {
            @Override
            public int compare(T o1, T o2) {
                try {
                    int result = contrast(o1, o2, fieldLabel);
                    if (result > 0) {
                        if (SortType.ASC.equals(sortType)) {
                            return 1;
                        } else {
                            return -1;
                        }
                    } else if (result < 0) {
                        if (SortType.ASC.equals(sortType)) {
                            return -1;
                        } else {
                            return 1;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
    }

    /**
     * 排序规则
     */
    public enum SortType{
        /**正序*/
        ASC,
        /**倒序*/
        DESC;
    }

/**
     * 字段比较
     * @param o1
     * @param o2
     * @param fieldLabel
     * @param <T>
     * @return
     * @throws NoSuchFieldException
     * @throws SecurityException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    protected static <T> int contrast(T o1, T o2, String fieldLabel)
            throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
        Field f1 = o1.getClass().getDeclaredField(fieldLabel);
        f1.setAccessible(true);
        Field f2 = o2.getClass().getDeclaredField(fieldLabel);
        f2.setAccessible(true);
        Class<?> clazz = f1.getType();
        int retVal;
        if (clazz.equals(String.class)) {
            retVal = f1.get(o1).toString().compareTo(f2.get(o2).toString());
        } else if (clazz == Float.class || clazz == float.class) {
            retVal = BigDecimal.valueOf((Float)f1.get(o1)).compareTo(BigDecimal.valueOf((Float)f2.get(o2)));
        } else if (clazz == Double.class || clazz == double.class) {
            retVal = BigDecimal.valueOf((Double)f1.get(o1)).compareTo(BigDecimal.valueOf((Double)f2.get(o2)));
        } else if (clazz == Integer.class || clazz == int.class) {
            retVal = BigDecimal.valueOf((Integer)f1.get(o1)).compareTo(BigDecimal.valueOf((Integer)f2.get(o2)));
        } else if (clazz == Short.class || clazz == short.class) {
            retVal = BigDecimal.valueOf((Short)f1.get(o1)).compareTo(BigDecimal.valueOf((Short)f2.get(o2)));
        } else if (clazz == Long.class || clazz == long.class) {
             retVal = BigDecimal.valueOf((Long)f1.get(o1)).compareTo(BigDecimal.valueOf((Long)f2.get(o2)));
        } else if (clazz == Byte.class || clazz == byte.class) {
             retVal = BigDecimal.valueOf((Byte)f1.get(o1)).compareTo(BigDecimal.valueOf((Byte)f2.get(o2)));
        } else if (clazz == BigDecimal.class) {
            BigDecimal a = new BigDecimal(f1.get(o1).toString());
            BigDecimal b = new BigDecimal(f2.get(o2).toString());
            retVal = a.compareTo(b);
        } else if (clazz == Date.class) {
            Date date1 = (Date) f1.get(o1);
            Date date2 = (Date) f1.get(o2);
            retVal = BigDecimal.valueOf(date1.getTime()).compareTo(BigDecimal.valueOf(date2.getTime()));
        } else {
            retVal = 0;
        }
        return retVal;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值