对List排序,多重排序,通用各种对象的多重排序

package util;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 排序类,通用于获取的对象的方法值 都是int类型
 *
 * @author chenjy
 *
 */
public final class SortUtil {
    /**
     * 装载已经用过的规则 实现类似单例模式
     */
    private static Map<String, SortUtil> sortMap = new HashMap<String, SortUtil>();

    private Method[] methodArr = null;
    private int[] typeArr = null;

    /**
     * 构造函数 并保存该规则
     *
     * @param clazz
     * @param args
     */
    private <T> SortUtil(Class<T> clazz, String... args) {
        methodArr = new Method[args.length];
        typeArr = new int[args.length];
        for (int i = 0; i < args.length; i++) {
            String key = args[i].split("#")[0];
            try {
                methodArr[i] = clazz.getMethod(key, new Class[] {});
                typeArr[i] = Integer.valueOf(args[i].split("#")[1]);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

    /**
     * 排序规则
     *
     * @author chenjy 2012-03-13
     */
    private Comparator<Object> comparator = new Comparator<Object>() {
        @Override
        public int compare(Object o1, Object o2) {
            for (int i = 0; i < methodArr.length; i++) {
                try {
                    Object value1 = methodArr[i].invoke(o1);
                    Object value2 = methodArr[i].invoke(o2);
                    double double1 = 0;
                    double double2 = 0;

                    if (value1 instanceof Integer) {
                        double1 = (Integer) value1;
                        double2 = (Integer) value2;
                    } else if (value1 instanceof Boolean) {
                        double1 = (Boolean) value1 ? 1 : -1;
                        double2 = (Boolean) value2 ? 1 : -1;
                    } else if (value1 instanceof Double) {
                        double1 = (Double) value1;
                        double2 = (Double) value2;
                    } else if (value1 instanceof Float) {
                        double1 = (Float) value1;
                        double2 = (Float) value2;
                    } else if (value1 instanceof Long) {
                        double1 = (Long) value1;
                        double2 = (Long) value2;
                    } else {
                        double1 = value1.toString().compareToIgnoreCase(
                                value2.toString());
                        double2 = -double1;
                    }
                    if (double1 == double2) {
                        continue;
                    }
                    if (typeArr[i] == 1) {
                        return (double1 > double2) ? 1 : -1;
                    } else {
                        return (double1 > double2) ? -1 : 1;
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
            return 0;
        }
    };

    /**
     * 获取排序规则 2012-3-13
     *
     * @return SortUtil
     * @author chenjy
     */
    private static <T> SortUtil getSort(Class<T> clazz, String... args) {
        String key = clazz.getName() + Arrays.toString(args);
        if (sortMap.containsKey(key)) {
            return sortMap.get(key);
        } else {
            SortUtil sort = new SortUtil(clazz, args);
            sortMap.put(key, sort);
            return sort;
        }
    }

    /**
     * <pre>
     * 首先会在容器中,根据class+规则去找。如果没有见则new
     * 调用方式 SortUtil.sort(list,"方法名#升序(1)/降序(-1)","..","..")
     * 后面字符串参数:比如:"getMark#1","getAge#-1"
     * 表示先按照getMark的值按照升序排,如果相等再按照getAge的降序排
     * 如果返回值是true类型,若按照true先排:"isOnline#1" ,若按照false先排:"isOnline#-1"
     * </pre>
     *
     * @author chenjy 2012-3-13
     * @param list
     * @param args
     */
    public static <T> void sort(List<T> list, String... args) {
        if (list == null || list.size() == 0 || args.length == 0) {
            return;
        }
        SortUtil sort = getSort(list.get(0).getClass(), args);
        Collections.sort(list, sort.comparator);
    }

    /**
     * 给Map进行排序 对map的value进行排序
     *
     * @author chenjy 2012-3-13
     * @param map
     *            被排序的map
     * @param args
     *            排序方法条件:方法名x#1升序-1倒序, 方法名y#-1倒序
     * @return List<T>
     */
    public static <T, F> List<F> sortMap(Map<T, F> map, String... args) {
        List<F> list = new ArrayList<F>();
        if (map == null || map.isEmpty()) {
            return list;
        }
        list.addAll(map.values());
        sort(list, args);
        return list;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
对自定义list对象排序也可以使用Collections.sort()方法,但是需要实现Comparable接口或者传入Comparator对象进行排序。下面给出两种实现方式。 1. 实现Comparable接口 如果自定义的对象实现了Comparable接口,那么可以直接使用Collections.sort()方法进行排序。示例代码如下: ```java public class Person implements Comparable<Person> { private String name; private int age; // 构造函数、getter和setter方法省略 @Override public int compareTo(Person o) { // 按照年龄从小到大排序 return Integer.compare(this.age, o.getAge()); } } // 对Person对象List进行排序 List<Person> personList = new ArrayList<>(); personList.add(new Person("Alice", 20)); personList.add(new Person("Bob", 18)); personList.add(new Person("Charlie", 22)); Collections.sort(personList); System.out.println(personList); ``` 2. 传入Comparator对象 如果自定义的对象没有实现Comparable接口,或者需要按照不同的方式进行排序,可以传入Comparator对象进行排序。示例代码如下: ```java public class Person { private String name; private int age; // 构造函数、getter和setter方法省略 } // 按照年龄从大到小排序的Comparator Comparator<Person> ageComparator = Comparator.comparingInt(Person::getAge).reversed(); // 对Person对象List进行排序 List<Person> personList = new ArrayList<>(); personList.add(new Person("Alice", 20)); personList.add(new Person("Bob", 18)); personList.add(new Person("Charlie", 22)); Collections.sort(personList, ageComparator); System.out.println(personList); ``` 注意,在传入Comparator对象进行排序时,需要使用Comparator.comparing()方法指定排序字段,并使用reversed()方法进行降序排序

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值