java通用实现List<自定义对象>中指定字段和指定排序方式

Person类:

/**
 * @date 2023/12/19 11:20
 */
public class Person {
    private String name;
    private String sex;

    public Person() {
    }

    public Person(String name, String sex) {
        this.name = name;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public String getSex() {
        return sex;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

工具类:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @date 2023/12/22 14:30
 */
public class SortListObjUtils {

    public final static String SORT_FIELD_PIX = "get";
    public final static String SORT_METHOD_DESC = "desc";
    public final static String SORT_METHOD_ASC = "asc";

    /**
     * 反射方式
     *
     * @param targetList 目标排序
     * @param sortField  排序字段-实体类属性名,例如: private String name;
     * @param sortMethod 排序方式-asc or desc
     */
    public static  void sortObjList(List targetList, final String sortField, final String sortMethod) {
        Collections.sort(targetList, new Comparator() {
            @Override
            public int compare(Object obj1, Object obj2) {
                int retVal = 0;
                try {
                    // 首字母转大写
                    String newString = sortField.substring(0, 1).toUpperCase() + sortField.replaceFirst("\\w", "");
                    // 生成getter方法,例如 getName
                    String methodString = SORT_FIELD_PIX + newString;

                    Method method1 = ((T) obj1).getClass().getMethod(methodString, null);
                    Method method2 = ((T) obj2).getClass().getMethod(methodString, null);
                    if (sortMethod != null && Objects.equals(SORT_METHOD_DESC, sortMethod)) {
                        retVal = method2.invoke(((T) obj2), null).toString().compareTo(method1.invoke(((T) obj1), null).toString()); // 倒序
                    } else {
                        retVal = method1.invoke(((T) obj1), null).toString().compareTo(method2.invoke(((T) obj2), null).toString()); // 正序
                    }
                } catch (Exception e) {
                    throw new RuntimeException();
                }
                return retVal;
            }
        });
    }


    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        // Person的修饰符一定要是public
        List personList = new ArrayList<>();
        Person person1 = new Person("1", "m");
        Person person2 = new Person("4", "f");
        Person person3 = new Person("2", "f");
        personList.add(person1);
        personList.add(person2);
        personList.add(person3);

        // 倒序
        long start1 = System.currentTimeMillis();
        SortListObjUtils.sortObjList(personList, "name", SORT_METHOD_DESC);
        long end1 = System.currentTimeMillis();
        System.out.println("倒序方式耗时 " + (end1 - start1) + " 毫秒");
        for (Person person : personList) {
            System.out.println("name->" + person.getName() + "  sex->" + person.getSex());
        }

        // 序序
        long start2 = System.currentTimeMillis();
        SortListObjUtils.sortObjList(personList, "name", SORT_METHOD_ASC);
        long end2 = System.currentTimeMillis();
        System.out.println("升序方式耗时 " + (end2 - start2) + " 毫秒");
        for (Person person : personList) {
            System.out.println("name->" + person.getName() + "  sex->" + person.getSex());
        }
    }
}

结果:

java通用实现List<自定义对象>中指定字段和指定排序方式_第1张图片

你可能感兴趣的:(java,开发语言)