欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

实体List转Map帮助类

程序员文章站 2022-06-15 12:08:14
...

import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeanUtil {

    /**
     * @param list
     * @param prokey 实体对应键
     * @param <T>
     * @return
     */
    public static <T>Map<String,T> listByMap(List<T> list,String prokey){
        Map<String,T> map = new HashMap<>();
        for (T t:list){
            String key;
            try {
                key = BeanUtils.getSimpleProperty(t,prokey);
            }catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                e.printStackTrace();
                throw new BizException(e.toString());
            }
            map.put(key,t);
        }
        return map;
    }
}