项目中需要将list进行组装,多处用到以下两种情况,封装成工具类可直接使用
前一个list为主,后一个list组装到前一个list中。
场景一
两个List<Map> 按照某个属性组装,后一个list<Map> 加到前一个List<Map>中
public void dataAssembly(List<Map<String,Object>> list, String fieldName, List<Map<String,Object>> dataLiat , String toFieldName) {
if(CollectionUtils.isEmpty(dataLiat)){
return;
}
Map<String,Map> dataMap = getDataMap(dataLiat,toFieldName);
try {
for (Map<String,Object> map : list) {
String id = (String) map.get(fieldName);
if (StringUtils.isEmpty(id)) {
continue;
}
dataAssembly(map, id, dataMap);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Map<String,Map> getDataMap(List dataLiat,String toFieldName){
Map<String,Map> dataMap = new HashMap();
for (Object dto : dataLiat) {
HashMap map = (HashMap) dto;
String returnId = (String) map.get(toFieldName);
if (returnId == null) {
continue;
}
dataMap.put(returnId.trim(),map);
}
return dataMap;
}
public void dataAssembly(Map<String,Object> obj, String id, Map<String,Map> dataMap){
Map map = dataMap.get(id.trim());
if (map == null) {
return;
}
obj.putAll(map);
}
场景二
一个List<Entity> 一个List<Map> 按照某个属性进行组装
public void dataAssembly(List list, String fieldName, List<Map<String,Object>> dataLiat , String toFieldName){
try {
if(CollectionUtils.isEmpty(list)){
return;
}
if(CollectionUtils.isEmpty(dataLiat)){
return;
}
Class objClass = list.get(0).getClass();
Field field = objClass.getDeclaredField(fieldName);
field.setAccessible(true);
for (Object obj : list) {
String id = (String) field.get(obj);
dataAssembly(obj,id,dataLiat,toFieldName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void dataAssembly(Object obj, String id, List list, String fieldName) throws Exception {
for (Object dto : list) {
HashMap map = (HashMap) dto;
String returnId = (String) map.get(fieldName);
if (returnId == null) {
continue;
}
if (!id.equals(returnId)) {
continue;
}
mapToBean(map, obj);
return;
}
}
public void mapToBean(Map<String, Object> map, Object obj) throws Exception {
Class objClass = obj.getClass();
Field[] fields = objClass.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Object value = map.get(field.getName());
if (value == null) {
continue;
}
field.set(obj, value);
}
}