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());
        }
    }
}

结果:

相关推荐
努力的lpp8 分钟前
php反序列化一(大白话版)
开发语言·web安全·php·ctf·反序列化
菜鸟~noob23316 分钟前
【电子战】第03篇:CFAR(恒虚警)处理【含matlab代码】
开发语言·matlab
lhldsg1 小时前
全民健身解决方案小程序开发:从0到1的技术实战
java·数据库·需求分析
jason成都1 小时前
Spring WebFlux 适配达梦新方案|dm‑r2dbc:Netty 异步传输的实验性 R2DBC 驱动
java·后端·spring
泡海椒1 小时前
内置SPI函数库详解:JQuick-Java Builtin工具类实战用法
java·开发语言·python
hqyjzsb1 小时前
零 AI 项目经验,学 Python 转型 AI 的正确顺序是什么?
开发语言·人工智能·python·算法·职场和发展·数据挖掘·数据分析
辰烨chenye1 小时前
LeetCode Hot 100 题解 · 二分篇
java·算法·leetcode
小羊没烦恼!2 小时前
Hello Web API系列教程——Web API与国际化
java·服务器·前端·javascript·php
Keven_112 小时前
算法札记:ACM适用的很骚的C++语法(持续更新)
开发语言·c++
脉动数据行情13 小时前
C# 实现德指 DAX 期货 WebSocket 实时行情监听
开发语言·websocket·c#