[工具类] Map的util包, 常用 实体类转化为map等操作

目录

 map工具类 常用

例子: json串转换map

例子: 将map的key放入list

例子: 将实体类转化为map


 map工具类 常用

例子: json串转换map

例子: 将map的key放入list

例子: 将实体类转化为map

等等 <==> 操作 整合

package com.aisce.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * @version 1.0.0
 */
public class MapUtil {
    private static final Logger logger = LoggerFactory.getLogger(MapUtil.class);

    /**
     * 复制 MAP, 浅拷贝
     * @param source 数据源
     * @param <T> 实体BEAN
     * @return 新map
     */
    public static <T> Map<String, T> cloneMap(Map<String, T> source){
        Map<String, T> target = new HashMap<>();
        for (Map.Entry<String, T> entry : source.entrySet()) {
            String key = entry.getKey();
            T value = entry.getValue();
            target.put(key, value);
        }
        return target;
    }

    /**
     * 对List进行分组存储
     * @param list 数据源
     * @param keyProperty KEY属性名
     * @return groupMap
     */
    public static <V> Map<String, List<Map<String, V>>> groupListToMap(List<Map<String, V>> list, String keyProperty){
        Map<String, List<Map<String, V>>> groupMap = new LinkedHashMap<>();
        for (Map<String, V> info : list){
            V key = info.get(keyProperty);
            if(key == null) { continue; }
            List<Map<String, V>> value = groupMap.get(key.toString());
            if (value == null){
                value = new ArrayList<>();
                groupMap.put(key.toString(), value);
            }
            value.add(info);
        }
        return groupMap;
    }

    /**
     * 对List进行分组存储, 用于JSON字符串转换为MAP使用
     * @param list 数据源
     * @param keyProperty KEY属性名
     * @return groupMap
     */
    public static Map<String, List<Map>> groupListToMap2(List<Map> list, String keyProperty){
        Map<String, List<Map>> groupMap = new LinkedHashMap<>();
        for (Map info : list){
            Object key = info.get(keyProperty);
            if(key == null) { continue; }
            List<Map> value = groupMap.get(key.toString());
            if (value == null){
                value = new ArrayList<>();
                groupMap.put(key.toString(), value);
            }
            value.add(info);
        }
        return groupMap;
    }

    /**
     * 对List进行分组存储
     * @param list 数据源
     * @param keyProperty KEY属性名
     * @param <T> 实体BEAN
     * @return groupMap
     */
    public static <T> Map<String, List<T>> getGroupMap(List<T> list, String keyProperty){
        Map<String, List<T>> groupMap = new LinkedHashMap<>();
        for (T info : list){
            Object key = BeanUtil.getValue(info, keyProperty);
            if(key == null) { continue; }
            List<T> value = groupMap.get(key.toString());
            if (value == null){
                value = new ArrayList<>();
                groupMap.put(key.toString(), value);
            }
            value.add(info);
        }
        return groupMap;
    }

    /**
     * 对List进行分组存储, key = id + property
     * @param list 数据源
     * @param keyProperty KEY属性名
     * @param idProperty ID
     * @param <T> 实体BEAN
     * @return
     */
    public static <T> Map<String, List<T>> getGroupMap(List<T> list, String keyProperty, String idProperty){
        Map<String, List<T>> groupMap = new LinkedHashMap<>();
        for (T info : list){
            Object property = BeanUtil.getValue(info, keyProperty);
            Object id = BeanUtil.getValue(info, idProperty);
            if(property == null || id == null) { continue; }
            String key = id.toString() +"-"+ property.toString();
            List<T> value = groupMap.get(key);
            if (value == null){
                value = new ArrayList<>();
                groupMap.put(key, value);
            }
            value.add(info);
        }
        return groupMap;
    }

    /**
     * 将map的key转换为List
     * @param source 数据源
     * @param <K> key
     * @param <V> value
     * @return list
     */
    public static <K, V> List<K> mapKeyToList(Map<K, V> source){
        List<K> list = new ArrayList<K>();
        for (Map.Entry<K, V> entry : source.entrySet()) {
            K key = entry.getKey();
            list.add(key);
        }
        return list;
    }

    /**
     * 将map的value转换为List
     * @param rowInfo 数据源
     * @param <V> 实体BEAN
     * @return list
     */
    public static <K, V> List<V> mapValueToList(Map<K, V> rowInfo){
        List<V> list = new ArrayList<V>();
        for(Iterator<K> keyIt = rowInfo.keySet().iterator(); keyIt.hasNext(); ){
            K key = keyIt.next();
            V value = rowInfo.get(key);
            list.add(value);
        }
        return list;
    }

    /**
     * 将map的value转换为List, 将指定属性的值存入list
     * @param rowInfo 数据源
     * @param columns 指定的key
     * @param <T> 实体BEAN
     * @return list
     */
    public static <T> List<T> mapToList(Map<String, T> rowInfo, String columns[]){
        List<T> list = new ArrayList<T>();
        for(String col : columns){
            T value = rowInfo.get(col);
            list.add(value);
        }
        return list;
    }

    /**
     * map转list,将MAP的每个键值对转换为一个新的MAP,存储在list中
     * @param source
     * @return List
     */
    public static <K, V> List<Map<String, Object>> mapToList(Map<K, V> source){
        List<Map<String, Object>> list = new ArrayList<>();
        for (Map.Entry<K, V> entry : source.entrySet()) {
            Map<String, Object> info = new HashMap<>();
            info.put("key", entry.getKey());
            info.put("value", entry.getValue());
            list.add(info);
        }
        return list;
    }

    /**
     * 实体类转map
     *
     * @param obj
     * @return
     */
    public static Map<String, Object> convertBeanToMap(Object obj) {
        if (obj == null) { return null; }
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // 过滤class属性
                if (!key.equals("class")) {
                    // 得到property对应的getter方法
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);
                    if (null == value) {
                        map.put(key, "");
                    } else {
                        map.put(key, value);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("convertBean2Map Error {}", e);
        }
        return map;
    }

    public static <T> Map convertMap(T obj){
        ObjectMapper objectMapper = new ObjectMapper();
        Map map = objectMapper.convertValue(obj, HashMap.class);
        return map;
    }

    public static <T> T convertBean(Map map, Class<T> clazz){
        ObjectMapper objectMapper = new ObjectMapper();
        T info = objectMapper.convertValue(map, clazz);
        return info;
    }

    /**
     * map转实体类
     * @param clazz 目标类
     * @param map 源数据
     * @return T
     */
    public static <T> T convertMapToBean(Class<T> clazz, Map<String, Object> map) {
        T obj = null;
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            obj = clazz.newInstance();
            // 给 JavaBean 对象的属性赋值
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (int i = 0; i < propertyDescriptors.length; i++) {
                PropertyDescriptor descriptor = propertyDescriptors[i];
                String propertyName = descriptor.getName();
                if (map.containsKey(propertyName)) {
                    Object value = map.get(propertyName);
                    Object[] args = new Object[1];
                    args[0] = value;
                    descriptor.getWriteMethod().invoke(obj, args);
                }
            }
        } catch (Exception e) {
            logger.warn("convertMapToBean 实例化JavaBean失败 {}" + e.getMessage());
        }
        return obj;
    }

    /**
     * 实体对象转成Map
     *
     * @param obj 实体对象
     * @return
     */
    public static Map<String, Object> object2Map(Object obj) {
        Map<String, Object> map = new HashMap<>();
        if (obj == null) {
            return map;
        }
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(obj));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * Map转成实体对象
     *
     * @param map   map实体对象包含属性
     * @param clazz 实体对象类型
     * @return
     */
    public static Object map2Object(Map<String, Object> map, Class<?> clazz) {
        if (map == null) {
            return null;
        }
        Object obj = null;
        try {
            obj = clazz.newInstance();
            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                field.setAccessible(true);
                field.set(obj, map.get(field.getName()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * map排序,默认升序
     * @param data 数据源
     * @param key 排序字段
     * @return
     */
    public static Map<String, Integer> sort(Map<String, Integer> data, String key){
        return sort(data, key, true);
    }

    /**
     * map排序
     * @param data 数据源
     * @param key 排序字段
     * @param asc true asc | false desc
     * @return
     */
    public static Map<String, Integer> sort(Map<String, Integer> data, String key, boolean asc){
        List<Map<String, Object>> list = mapToList(data);
        Collections.sort(list, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Integer v1 = Integer.valueOf(o1.get(key).toString());
                Integer v2 = Integer.valueOf(o2.get(key).toString());
                if (null == v1) {
                    return -1;
                }
                if (null == v2) {
                    return 1;
                }
                if(asc) { return v1.compareTo(v2); }
                return v2.compareTo(v1);
            }
        });

        Map<String, Integer> result = new LinkedHashMap<>();
        for (Map<String, Object> map : list){
            result.put(map.get("key").toString(), Integer.valueOf(map.get("value").toString()) );
        }
        return result;
    }

}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,可以使用 Java 自带的反射机制和递归实现将实体类换成 Map。以下是示例代码: ```java import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class EntityUtils { /** * 将实体类换成 Map * * @param object 实体类对象 * @return Map<String, Object> 对应的 Map */ public static Map<String, Object> entityToMap(Object object) { Map<String, Object> result = new HashMap<>(); Class<?> clazz = object.getClass(); Field[] fields = clazz.getDeclaredFields(); try { for (Field field : fields) { field.setAccessible(true); // 如果是 List 类型则递归调用本方法 if (field.getType() == List.class) { List<Object> list = new ArrayList<>(); List<?> tempList = (List<?>) field.get(object); for (Object temp : tempList) { list.add(entityToMap(temp)); } result.put(field.getName(), list); } else { result.put(field.getName(), field.get(object)); } } } catch (IllegalAccessException e) { e.printStackTrace(); } return result; } } ``` 使用方法: ```java // 定义实体类 public class User { private String name; private Integer age; private List<String> hobbies; // 省略 getter 和 setter 方法 } // 创建实体类对象 User user = new User(); user.setName("Tom"); user.setAge(18); List<String> hobbies = new ArrayList<>(); hobbies.add("Reading"); hobbies.add("Swimming"); user.setHobbies(hobbies); // 调用工具类方法将实体类换成 Map Map<String, Object> map = EntityUtils.entityToMap(user); System.out.println(map); ``` 输出结果如下: ``` {name=Tom, age=18, hobbies=[{hobby=Reading}, {hobby=Swimming}]} ``` 可以看到,工具类成功地将实体类换成了对应的 Map括了 List 类型的属性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pingzhuyan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值