集合处理工具

 1 /**
 2      * 按给定对象属性为参数ls分组整理
 3      * @param ls 集合
 4      * @param propertyName 对象中的某个属性
 5      * @return HashMap(key=propertyValue,Value=ArrayList)
 6      * @throws IllegalAccessException
 7      * @throws InvocationTargetException
 8      * @throws NoSuchMethodException
 9      */
10     @SuppressWarnings("unchecked")
11     public static <T,E> HashMap<T,List<E>> groupByProperty(List<E> ls,String propertyName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
12         HashMap<T,List<E>> result=new HashMap<T,List<E>>();
13         List<E> list=null;
14         for (Iterator<E> iter = ls.iterator(); iter.hasNext();) {
15             E element = iter.next();
16             T proValue=(T)PropertyUtils.getProperty(element, propertyName);
17             if(proValue==null)
18                 throw new NullPointerException("propertyValue is null"); 
19             if(result.containsKey(proValue)){
20                 list=(List<E>) result.get(proValue);
21             }else{
22                 list=new ArrayList<E>();
23                 result.put(proValue, list);
24             }
25             list.add(element);
26         }
27         return result;
28     }
 1     /**
 2      * 提取集合中的对象的属性,组合成List.
 3      * 
 4      * @param collection 来源集合.
 5      * @param propertyName 要提取的属性名.
 6      */
 7     @SuppressWarnings({ "unchecked", "rawtypes" })
 8     public static List fetchElementPropertyToList(final Collection collection, final String propertyName) throws Exception {
10         List list = new ArrayList();
11         for (Object obj : collection) {
12             list.add(PropertyUtils.getProperty(obj, propertyName));
13         }
14 
15         return list;
16     }
原文地址:https://www.cnblogs.com/sun-space/p/5562017.html