MapUtils.java
1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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))));
}
}