一、使用场景
1.当从数据库中获取了一个对象集合后,如果需要得到这个集合里面每个对象的某个值。可以使用工具类将该值提取成一个新的集合,以便操作。
2.当从数据库中获取了一个对象集合后,如果需要得到这个集合里面每个对象的两个值形成的map集合,也是可以使用工具类将这两个值提取成一个map,以便操作。
二、代码
package com.porty.util;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;
public class PortyCollectionOrMapUtil {
private static final String PREFIX_GET = "get";
public static HashMap<Object,Object> listTransformMap(List list, Class clazz, String param1, String param2) throws Exception {
try {
param1 = param1.replaceFirst(param1.substring(0,1), param1.substring(0,1).toUpperCase());
param2 = param2.replaceFirst(param2.substring(0,1), param2.substring(0,1).toUpperCase());
} catch (Exception e) {
throw new PortyException("param1 or param2 is empty!");
}
HashMap map = new HashMap();
Method[] methods = clazz.getMethods();
Method method1 = null;
Method method2 = null;
for (Method method : methods) {
if(method1!=null && method2!=null) {
break;
}
if(method.getName().equals(PREFIX_GET + param1)) {
method1 = method;
}else if(method.getName().equals(PREFIX_GET + param2)) {
method2 = method;
}
}
if(method1!=null&&method2!=null) {
for (Object object : list) {
map.put(method1.invoke(object),method2.invoke(object));
}
return map;
}
return map;
}
public static List transformParamList(List list, Class clazz, String param) throws Exception {
try {
param = param.replaceFirst(param.substring(0,1), param.substring(0,1).toUpperCase());
} catch (Exception e) {
throw new PortyException("param is empty!");
}
List rst = new ArrayList();
Method[] methods = clazz.getMethods();
Method method1 = null;
for (Method method : methods) {
if(method1!=null) {
break;
}
if(method.getName().equals(PREFIX_GET + param)) {
method1 = method;
}
}
if(method1!=null) {
for (Object object : list) {
rst.add(method1.invoke(object));
}
return rst;
}
return rst;
}
public static Set transformParamSet(List list, Class clazz, String param) throws Exception {
return (Set)transformParamList(list, clazz, param).stream().collect(Collectors.toSet());
}
}