当前位置:网站首页>[工具类] Map的util包, 常用 实体类转化为map等操作
[工具类] Map的util包, 常用 实体类转化为map等操作
2022-07-28 18:49:00 【pingzhuyan】
目录
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;
}
}
边栏推荐
- 平均海拔4000米!我们在世界屋脊建了一朵云
- How to balance security and performance in SQL?
- 全链路灰度在数据库上我们是怎么做的?
- 太空射击第11课: Sound and Music
- 3D激光SLAM:LeGO-LOAM论文解读---简介部分
- View the thread stack according to the lwtid of opengauss/mogdb.
- Ask if you don't understand, and quickly become an advanced player of container service!
- Easynlp Chinese text and image generation model takes you to become an artist in seconds
- Report redirect after authorized login on wechat official account_ The problem of wrong URI parameters
- 关于正则的两道笔试面试题
猜你喜欢
Database tuning - connection pool optimization

Want to draw a picture that belongs to you? AI painting, you can also

How to use redis to realize things and locks?

有奖征文 | 2022 云原生编程挑战赛征稿活动开启

Redis的三种删除策略以及逐出算法

Redis 3.0 source code analysis - data structure and object SDS list Dict

LVM logical volume

Use of DDR3 (axi4) in Xilinx vivado (1) create an IP core

Unity performance optimization

Read the recent trends of okaleido tiger and tap the value and potential behind it
随机推荐
云原生编程挑战赛火热开赛,51 万奖金等你来挑战!
About IP address
Three steps to teach you unity serial communication
7/27 training log (bit operation + suffix array)
Unity performance optimization
Soft raid
[C语言刷题篇]链表运用讲解
Read the recent trends of okaleido tiger and tap the value and potential behind it
About the title of linking to other pages
网络各层性能测试
Yyds dry inventory interview must brush top101: every k nodes in the linked list are turned over
View the thread stack according to the lwtid of opengauss/mogdb.
一文了解 Rainbond 云原生应用管理平台
想画一张版权属于你的图吗?AI作画,你也可以
How to balance security and performance in SQL?
Explain the life cycle function in unity in detail
漂亮的蓝色背景表单输入框样式
Redis 3.0源码分析-数据结构与对象 SDS LIST DICT
How to use redis to realize things and locks?
How to make the design of governance structure more flexible when the homogenization token is combined with NFT?