在日常开发中,会遇到将两个不同对象类型的list按照某个属性进行整合
例如 :
List<obj1> obj1List ,List<obj2> obj2List,需要按照obj1.id=obj2.id进行整合
select * from obj1List left join obj2List on obj1.id=obj2.id
-
第一步:将obj1List转换成map
将list转成id为key,obj1为value的map对象public static <K, V> Map<K, V> listToMap(List<V> list, String keyMethodName, Class<V> c) { Map<K, V> map = new HashMap<K, V>(); if (list != null) { try { Method methodGetKey = c.getMethod(keyMethodName); for (int i = 0; i < list.size(); i++) { V value = list.get(i); @SuppressWarnings("unchecked") K key = (K) methodGetKey.invoke(list.get(i)); map.put(key, value); } } catch (Exception e) { throw new IllegalArgumentException("field can't match the key!"); } } return map; }
-
第二步:根据key值将obj2List进行copy
for (Obj2 obj: obj2List) { try { System.out.println(obj); BeanUtils.copyProperties(mapFromList1.get(obj.getId()), obj); } catch (Exception e) { e.printStackTrace(); } }
网友评论