List集合分组依据集合中对象的属性

 

直接上代码

用到了Spring的BeanWrapper类

public static <T, K> Map<K, List<T>> groupByProperty(Collection<T> collection, String propertyName, Class<K> clazz) {
Map<K, List<T>> map = new HashMap<K, List<T>>();
for (T item : collection) {
BeanWrapper beanWrapper = new BeanWrapperImpl(item);
@SuppressWarnings("unchecked")
K key = (K) beanWrapper.getPropertyValue(propertyName);
List<T> list = map.get(key);
if (null == list) {
list = new ArrayList<T>();
map.put(key, list);
}
list.add(item);
}
return map;
}

posted on 2016-09-07 10:31  Snowman-Nunu  阅读(1223)  评论(0编辑  收藏  举报

导航