当前位置:网站首页>[tool class] util package of map, common entity classes are converted to map and other operations
[tool class] util package of map, common entity classes are converted to map and other operations
2022-07-28 20:58:00 【pingzhuyan】
Catalog
Example : json String conversion map
Example : take map Of key Put in list
Example : Convert the entity class to map
map Tool class Commonly used
Example : json String conversion map
Example : take map Of key Put in list
Example : Convert the entity class to map
wait <==> operation Integrate
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);
/**
* Copy MAP, Shallow copy
* @param source data source
* @param <T> Entity BEAN
* @return new 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;
}
/**
* Yes List Group storage
* @param list data source
* @param keyProperty KEY Property name
* @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;
}
/**
* Yes List Group storage , be used for JSON String conversion to MAP Use
* @param list data source
* @param keyProperty KEY Property name
* @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;
}
/**
* Yes List Group storage
* @param list data source
* @param keyProperty KEY Property name
* @param <T> Entity 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;
}
/**
* Yes List Group storage , key = id + property
* @param list data source
* @param keyProperty KEY Property name
* @param idProperty ID
* @param <T> Entity 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;
}
/**
* take map Of key Convert to List
* @param source data 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;
}
/**
* take map Of value Convert to List
* @param rowInfo data source
* @param <V> Entity 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;
}
/**
* take map Of value Convert to List, Store the value of the specified attribute in list
* @param rowInfo data source
* @param columns designated key
* @param <T> Entity 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 turn list, take MAP Each key value pair of is converted to a new MAP, Stored in list in
* @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;
}
/**
* Entity class to 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();
// Filter class attribute
if (!key.equals("class")) {
// obtain property Corresponding getter Method
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 Turn entity class
* @param clazz Target class
* @param map Source data
* @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();
// to JavaBean Object's property assignment
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 Instantiation JavaBean Failure {}" + e.getMessage());
}
return obj;
}
/**
* Convert entity objects to Map
*
* @param obj Entity object
* @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 Convert to entity object
*
* @param map map The entity object contains attributes
* @param clazz Entity object type
* @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 Sort , Default ascending order
* @param data data source
* @param key Sort field
* @return
*/
public static Map<String, Integer> sort(Map<String, Integer> data, String key){
return sort(data, key, true);
}
/**
* map Sort
* @param data data source
* @param key Sort field
* @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;
}
}
边栏推荐
- Leetcode:2141. The longest time to run n computers at the same time [the maximum value is two points]
- Unity object path query tool
- 怎样搭建企业内部维基百科
- [1331. Array serial number conversion]
- C # basic 5-asynchronous
- Redis 3.0 source code analysis - data structure and object SDS list Dict
- Explain in detail the rays and radiographic testing in unity
- Alibaba cloud MSE supports go language traffic protection
- Redis的三种删除策略以及逐出算法
- Use order by to sort
猜你喜欢

Introduction to redis I: redis practical reading notes

Unity foundation 2 editor expansion

Alibaba cloud MSE supports go language traffic protection

JS fly into JS special effect pop-up login box

Seventeen year operation and maintenance veterans, ten thousand words long, speak through the code of excellent maintenance and low cost~

prometheus配置alertmanager完整过程

JS page black and white background switch JS special effect

Confusing knowledge points of software designer examination

UE4 3dui widget translucent rendering blur and ghosting problems

What is "security"? Volvo tells you with its unique understanding and action
随机推荐
How do we do full link grayscale on the database?
Unity performance optimization
oracle如何导出数据(oracle如何备份数据库)
Establishment of flask static file service
远光软件获得阿里云产品生态集成认证,携手阿里云共建新合作
Three deletion strategies and eviction algorithm of redis
Explain prefabrication in unity in detail
How bad can a programmer be? Nima, they are all talents
Subcontracting loading of wechat applet
C# 读取 CSV文件内数据,导入DataTable后显示
Teach you unity scene switching progress bar production hand in hand
Space shooting Lesson 15: props
Prometheus complete process of configuring alertmanager
到底为什么不建议使用SELECT * ?
【ADB常用命令及其用法大全(来自[醒不了的星期八]的全面总结)】
Unity foundation 2 editor expansion
Alibaba cloud MSE supports go language traffic protection
云原生编程挑战赛火热开赛,51 万奖金等你来挑战!
Explain various coordinate systems in unity in detail
UE4 3dui widget translucent rendering blur and ghosting problems