当前位置:网站首页>[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;
}
}
边栏推荐
- 怎样搭建企业内部维基百科
- 《软件设计师考试》易混淆知识点
- Three steps to teach you unity serial communication
- Beautiful blue background form input box style
- "When you are no longer a programmer, many things will get out of control" -- talk to SUSE CTO, the world's largest independent open source company
- JS chart scatter example
- High beam software has obtained Alibaba cloud product ecological integration certification, and is working with Alibaba cloud to build new cooperation
- 企业如何成功完成云迁移?
- #yyds干货盘点# 面试必刷TOP101:链表中的节点每k个一组翻转
- Seventeen year operation and maintenance veterans, ten thousand words long, speak through the code of excellent maintenance and low cost~
猜你喜欢

Three deletion strategies and eviction algorithm of redis

Laser slam:logo-loam --- code compilation, installation and gazebo test
Looking at SQL optimization from the whole process of one query

微信小程序的分包加载

Integrating database Ecology: using eventbridge to build CDC applications

阿里云 MSE 支持 Go 语言流量防护

Explain the camera in unity and its application

JS picture hanging style photo wall JS special effect

JS fly into JS special effect pop-up login box

How to balance security and performance in SQL?
随机推荐
C # basic 5-asynchronous
mfc wpf winform(工业用mfc还是qt)
[工具类] Map的util包, 常用 实体类转化为map等操作
Two written interview questions about regular
融合数据库生态:利用 EventBridge 构建 CDC 应用
7/27 training log (bit operation + suffix array)
UE4 3dui widget translucent rendering blur and ghosting problems
Fragment中使用ViewPager滑动浏览页面
不懂就问,快速成为容器服务进阶玩家!
The cloud native programming challenge is hot, with 510000 bonus waiting for you to challenge!
Space shooting lesson 14: player life
1 Introduction to command mode
Unity foundation 3- data persistence
Random talk on GIS data (VI) - projection coordinate system
Redis入门二:redhat 6.5安装使用
JS chart scatter example
Explain the camera in unity and its application
有奖征文 | 2022 云原生编程挑战赛征稿活动开启
ntp服务器 时间(查看服务器时间)
Oracle library access is slow. Why?