list排序 一个list基于另一个list排序


package com.eaton.guan.club.util;

import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @Author : hyx
 * @CreateDate : 2021-06-02 11:19
 */
public class ListUtil {

    /**
     * list排序 一个list基于另一个list排序
     * @param orderRegulation 有序list
     * @param targetList 无序list
     * @param fieldName 排序字段名称
     * @param <T>
     */
    public static <T> void setListOrder(List <Long> orderRegulation, List <T> targetList, String fieldName) {
        targetList.sort(((o1, o2) -> {
            int io1 = orderRegulation.indexOf(getObjectId(o1,fieldName));

            int io2 = orderRegulation.indexOf(getObjectId(o2,fieldName));

            if (io1 != -1) {
                io1 = targetList.size() - io1;

            }

            if (io2 != -1) {
                io2 = targetList.size() - io2;

            }
            return io2 - io1;

        }));
    }

    /**
     * 通过反射获取泛型中对象字段的值
     * @param inputObject 泛型对象
     * @param fieldName 需要获取的字段名称
     * @return
     */
    public static <T> Long getObjectId(T inputObject, String fieldName)  {
        Class <?> clazz = inputObject.getClass();
        PropertyDescriptor pd = null;
        try {
            Field field = inputObject.getClass().getDeclaredField(fieldName);
            pd = new PropertyDescriptor(field.getName(), clazz);
        } catch (Exception e) {}

        //传入类没有指定字段,就去父类上找
        if (StringUtils.isEmpty(pd)){
            try {
                Field declaredField = inputObject.getClass().getSuperclass().getDeclaredField(fieldName);
                Class <?> aClass = inputObject.getClass().getSuperclass();
                pd = new PropertyDescriptor(declaredField.getName(), aClass);
            } catch (Exception e) {}
        }

        //获得get方法
        Method getMethod = pd.getReadMethod();
        return (Long) ReflectionUtils.invokeMethod(getMethod, inputObject);
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值