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

Person类:

java 复制代码
/**
 * @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;
    }
}

工具类:

java 复制代码
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 <T> void sortObjList(List<T> 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<Person> 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());
        }
    }
}

结果:

相关推荐
步步为营DotNet1 小时前
深度解析CancellationToken:.NET中的优雅取消机制
java·前端·.net
冷雨夜中漫步8 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
JH30739 小时前
SpringBoot 优雅处理金额格式化:拦截器+自定义注解方案
java·spring boot·spring
m0_7369191010 小时前
C++代码风格检查工具
开发语言·c++·算法
Coder_Boy_10 小时前
技术让开发更轻松的底层矛盾
java·大数据·数据库·人工智能·深度学习
2501_9449347310 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
invicinble11 小时前
对tomcat的提供的功能与底层拓扑结构与实现机制的理解
java·tomcat
较真的菜鸟11 小时前
使用ASM和agent监控属性变化
java
黎雁·泠崖11 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
2301_7634724612 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法