MapUtils.java 1.7 KB
package com.glsx.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;


/**
 * @Description: 将实体类属性转为map
 * @author fengzhi
 * @version V1.0
 */
public class MapUtils {
    public static TreeMap<String, String> transBean2Map(Object obj) {

        if(obj == null){
            return null;
        }

        TreeMap<String, String> map = new TreeMap<String, String>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();

                // 过滤class属性
                if (!"class".equals(key)) {
                    // 得到property对应的getter方法
                    Method getter = property.getReadMethod();
                    String value = String.valueOf(getter.invoke(obj)) ;
                    map.put(key, value);
                }

            }
        } catch (Exception e) {
            System.out.println("transBean2Map Error " + e);
            e.printStackTrace();
        }

        return map;
    }

    /**
     * 方案一:直接转map,key直接设置,val的index由key计算
     * @Title: listToMap
     * @Description: 把两个List转换为Map
     */
    public static  <K, V> Map<K, V> listToMap(List<K> keys, List<V> values) {
        return keys.stream().collect(Collectors.toMap(key -> key, key -> values.get(keys.indexOf(key))));
    }
}