All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.zyy.common.util.ListUtil Maven / Gradle / Ivy

package com.zyy.common.util;

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

/**
 * 集合工具类
 *
 * @author li.yang
 */
public class ListUtil {
    /**
     * 升序
     */
    private static final String ASC = "asc";
    /**
     * 降序
     */
    private static final String DESC = "desc";

    /**
     * 列表排序
     *
     * @param list   许哟啊排序的集合
     * @param method 需要排序的字段
     * @param sort   升序降序
     * @param     泛型
     */
    public static  void sort(List list, final String method, final String sort) {
        list.sort((a, b) -> {
            int ret = 0;
            try {
                Method m1 = a.getClass().getMethod(method);
                Method m2 = b.getClass().getMethod(method);
                if (DESC.equals(sort))
                    ret = (m2.invoke(b) == null ? "" : m2.invoke(b).toString()).compareTo((m1.invoke(a) == null ? "" : m1.invoke(a).toString()));
                else if (ASC.equals(sort))
                    ret = (m1.invoke(a) == null ? "" : m1.invoke(a).toString()).compareTo((m2.invoke(b) == null ? "" : m2.invoke(b).toString()));
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ne) {
                System.out.println(ne);
            }
            return ret;
        });
    }

    /**
     * 按升序排序
     *
     * @param list   许哟啊排序的集合
     * @param method 需要排序的字段
     * @param     泛型
     */
    public static  void sortAsc(List list, final String method) {
        sort(list, method, ASC);
    }

    /**
     * 按降序排序
     *
     * @param list   许哟啊排序的集合
     * @param method 需要排序的字段
     * @param     泛型
     */
    public static  void sortDesc(List list, final String method) {
        sort(list, method, DESC);
    }

    /**
     * 按属性拆分集合
     *
     * @param list 需要拆分的集合
     * @return 拆分后的集合key为属性值
     */
    public static  Map> splitListByParam(Collection list, String param) throws IllegalAccessException {
        Map> map = new HashMap<>();
        for (T detail : list) {
            Field field = ReflexUtil.getFiled(detail, param);
            field.setAccessible(true);
            String key = field.get(detail).toString();
            if (!map.containsKey(key)) {
                map.put(key, Collections.singletonList(detail));
            } else {
                map.get(key).add(detail);
            }
        }
        return map;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy