直接上代码
用到了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;
}