Java对象集合万能排序封装

31次阅读

共计 4220 个字符,预计需要花费 11 分钟才能阅读完成。

前言

直接进入正题,闲的没事把 Java 对对象集合排序进行了封装,写起来优雅一点,不用每次用的时候自己再 new 一个比较器对象了。

ListOrderUtil

没多少东西,就是下边这点代码!

import java.lang.reflect.Field;
import java.util.*;

public class ListOrderUtil<T> {
    private List<T> mArrayList;// 数据集合
    private HashMap<String, Integer> mOrderList = new HashMap<>();// 所有的排序字段
    private Class mClass;// 当天 T 的 Class
    public static int ORDER_ASC = 1;// 正序排列
    public static int ORDER_DESC = 2;// 倒序排列

    public ListOrderUtil(List<T> arrayList, Class<T> tClass) {
        this.mArrayList = arrayList;
        this.mClass = tClass;
    }

    /**
     * 设置排序字段(按照设置的先后顺序对其进行排序)*
     * @param fieldName    字段名称
     * @param orderPattern 排序模式
     * @return
     */
    public ListOrderUtil setOrderField(String fieldName, int orderPattern) {this.mOrderList.put(fieldName, orderPattern);
        return this;
    }

    /**
     * 对数据集合进行排序
     *
     * @return
     */
    public List<T> order() {this.mArrayList.sort(new Comparator<T>() {
            @Override
            public int compare(T o1, T o2) {
                Field field = null;
                int order = 0;
                for (Map.Entry<String, Integer> item : mOrderList.entrySet()) {
                    try {field = mClass.getDeclaredField(item.getKey());
                        field.setAccessible(true);
                        if (field == null) {throw new NoSuchFieldException(item.getKey());
                        }
                        if (item.getValue() == ORDER_ASC) {order = field.get(o1).toString().compareTo(field.get(o2).toString());
                        } else {order = field.get(o2).toString().compareTo(field.get(o1).toString());
                        }
                        if (order != 0) {return order;}
                    } catch (Exception e) {e.printStackTrace();
                    }
                }
                return 0;
            }
        });
        return this.mArrayList;
    }
}

使用案例

首先是对象一枚!

import java.util.Comparator;

public class Students {
    private int studentId;
    private int age;
    private String studentName;

    public Students() {}

    public Students(int studentId, int age, String studentName) {
        this.studentId = studentId;
        this.age = age;
        this.studentName = studentName;
    }

    public int getStudentId() {return studentId;}

    public void setStudentId(int studentId) {this.studentId = studentId;}

    public int getAge() {return age;}

    public void setAge(int age) {this.age = age;}

    public String getStudentName() {return studentName;}

    public void setStudentName(String studentName) {this.studentName = studentName;}

}

先来看看不封装的时候如何排序:

大量的逻辑处理代码冗余 ……

public class Main {public static void main(String[] args) {

        // 添加测试数据
        ArrayList<Students> students = new ArrayList<>();

        Students students1 = new Students(1001, 22, "djk");
        Students students2 = new Students(1002, 18, "xxh");
        Students students3 = new Students(1003, 31, "wyd");
        Students students4 = new Students(1002, 18, "wxz");
        Students students5 = new Students(1005, 19, "sxn");
        Students students6 = new Students(1004, 32, "ljc");

        students.add(students1);
        students.add(students2);
        students.add(students3);
        students.add(students4);
        students.add(students5);
        students.add(students6);
        //------------- 不封装的写法 ---------------------------- 不堪入目啊!!!!//1、使用 studentId 正序排列
        Collections.sort(students, new Comparator<Students>() {
            @Override
            public int compare(Students o1, Students o2) {return o1.getStudentId() - o2.getStudentId();}
        });
        //2、使用 studentId 和 age 进行多字段排序,studentId 正序为首,若想等便以 age 进行倒序排列。Collections.sort(students, new Comparator<Students>() {
            @Override
            public int compare(Students o1, Students o2) {int order = o1.getStudentId() - o2.getStudentId();
                if (order == 0) {order = o2.getAge() - o1.getAge();}
                return order;
            }
        });
        //3、多字段排序
        Collections.sort(students, new Comparator<Students>() {
            @Override
            public int compare(Students o1, Students o2) {int order = o1.getStudentId() - o2.getStudentId();
                if (order == 0) {order = o2.getAge() - o1.getAge();}
                if (order == 0) {order = o2.getStudentName().compareTo(o1.getStudentName());
                }
                return order;
            }
        });

    }
}

再来看看封装后的:

舒服多了 ……

public class Main {public static void main(String[] args) {

        // 添加测试数据
        ArrayList<Students> students = new ArrayList<>();

        Students students1 = new Students(1001, 22, "djk");
        Students students2 = new Students(1002, 18, "xxh");
        Students students3 = new Students(1003, 31, "wyd");
        Students students4 = new Students(1002, 18, "wxz");
        Students students5 = new Students(1005, 19, "sxn");
        Students students6 = new Students(1004, 32, "ljc");

        students.add(students1);
        students.add(students2);
        students.add(students3);
        students.add(students4);
        students.add(students5);
        students.add(students6);

        // 排序使用
        ListOrderUtil<Students> listOrderUtil = new ListOrderUtil<>(students, Students.class);
        //1、使用 studentId 正序排列
        listOrderUtil.setOrderField("studentId", ListOrderUtil.ORDER_ASC).order();

        //2、使用 studentId 和 age 进行多字段排序,studentId 正序为首,若想等便以 age 进行倒序排列。listOrderUtil.setOrderField("studentId", ListOrderUtil.ORDER_ASC)
                .setOrderField("age", ListOrderUtil.ORDER_DESC);

        //3、多字段排序
        listOrderUtil.setOrderField("studentId", ListOrderUtil.ORDER_ASC)
                .setOrderField("age", ListOrderUtil.ORDER_DESC)
                .setOrderField("studentName", ListOrderUtil.ORDER_DESC)
                .order();}
}

正文完
 0