JAVA 集合 List 分组的两种方法

来源:互联网 发布:美工陈列是做什么 编辑:程序博客网 时间:2024/05/22 16:47

实体类Data

[java] view plain copy
  1. public class Data {  
  2.   
  3.     private Long id ;  
  4.     private Long courseId ;  
  5.     private String content ;  
  6.   
  7.     public Long getId() {  
  8.         return id;  
  9.     }  
  10.   
  11.     public Data setId(Long id) {  
  12.         this.id = id;  
  13.         return this ;  
  14.     }  
  15.   
  16.     public Long getCourseId() {  
  17.         return courseId;  
  18.     }  
  19.   
  20.     public Data setCourseId(Long courseId) {  
  21.         this.courseId = courseId;  
  22.         return this ;  
  23.     }  
  24.   
  25.     public String getContent() {  
  26.         return content;  
  27.     }  
  28.   
  29.     public Data setContent(String content) {  
  30.         this.content = content;  
  31.         return this ;  
  32.     }  
  33.       
  34. }  

排序类

[java] view plain copy
  1. <pre name="code" class="java">import java.lang.reflect.Method;  
  2. import java.util.ArrayList;  
  3. import java.util.Collection;  
  4. import java.util.HashMap;  
  5. import java.util.Iterator;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8.   
  9. import com.framework.util.ParamUtils;  
  10.   
  11. public class CommonUtils {  
  12.   
  13.     /** 
  14.      * 分組依據接口,用于集合分組時,獲取分組依據 
  15.      *  
  16.      * @author ZhangLiKun 
  17.      * @title GroupBy 
  18.      * @date 2013-4-23 
  19.      */  
  20.     public interface GroupBy<T> {  
  21.         T groupby(Object obj);  
  22.     }  
  23.   
  24.     /** 
  25.      *  
  26.      * @param colls 
  27.      * @param gb 
  28.      * @return 
  29.      */  
  30.     public static final <T extends Comparable<T>, D> Map<T, List<D>> group(Collection<D> colls, GroupBy<T> gb) {  
  31.         if (colls == null || colls.isEmpty()) {  
  32.             System.out.println("分組集合不能為空!");  
  33.             return null;  
  34.         }  
  35.         if (gb == null) {  
  36.             System.out.println("分組依據接口不能為Null!");  
  37.             return null;  
  38.         }  
  39.         Iterator<D> iter = colls.iterator();  
  40.         Map<T, List<D>> map = new HashMap<T, List<D>>();  
  41.         while (iter.hasNext()) {  
  42.             D d = iter.next();  
  43.             T t = gb.groupby(d);  
  44.             if (map.containsKey(t)) {  
  45.                 map.get(t).add(d);  
  46.             } else {  
  47.                 List<D> list = new ArrayList<D>();  
  48.                 list.add(d);  
  49.                 map.put(t, list);  
  50.             }  
  51.         }  
  52.         return map;  
  53.     }  
  54.     /** 
  55.      * 将List<V>按照V的methodName方法返回值(返回值必须为K类型)分组,合入到Map<K, List<V>>中<br> 
  56.      * 要保证入参的method必须为V的某一个有返回值的方法,并且该返回值必须为K类型 
  57.      *  
  58.      * @param list 
  59.      *            待分组的列表 
  60.      * @param map 
  61.      *            存放分组后的map 
  62.      * @param clazz 
  63.      *            泛型V的类型 
  64.      * @param methodName 
  65.      *            方法名 
  66.      */  
  67.     public static <K, V> void listGroup2Map(List<V> list, Map<K, List<V>> map, Class<V> clazz, String methodName) {  
  68.         // 入参非法行校验  
  69.         if (null == list || null == map || null == clazz || !ParamUtils.chkString(methodName)) {  
  70.             System.out.print("CommonUtils.listGroup2Map 入参错误,list:" + list + " ;map:" + map + " ;clazz:" + clazz + " ;methodName:" + methodName);  
  71.             return;  
  72.         }  
  73.   
  74.         // 获取方法  
  75.         Method method = getMethodByName(clazz, methodName);  
  76.         // 非空判断  
  77.         if (null == method) {  
  78.             return;  
  79.         }  
  80.   
  81.         // 正式分组  
  82.         listGroup2Map(list, map, method);  
  83.     }  
  84.     /** 
  85.      * 根据类和方法名,获取方法对象 
  86.      *  
  87.      * @param clazz 
  88.      * @param methodName 
  89.      * @return 
  90.      */  
  91.     public static Method getMethodByName(Class<?> clazz, String methodName) {  
  92.         Method method = null;  
  93.         // 入参不能为空  
  94.         if (null == clazz || !ParamUtils.chkString(methodName)) {  
  95.             System.out.print("CommonUtils.getMethodByName 入参错误,clazz:" + clazz + " ;methodName:" + methodName);  
  96.             return method;  
  97.         }  
  98.   
  99.         try {  
  100.             method = clazz.getDeclaredMethod(methodName);  
  101.         } catch (Exception e) {  
  102.             System.out.print("类获取方法失败!");  
  103.         }  
  104.   
  105.         return method;  
  106.     }  
  107.     /** 
  108.      * 将List<V>按照V的某个方法返回值(返回值必须为K类型)分组,合入到Map<K, List<V>>中<br> 
  109.      * 要保证入参的method必须为V的某一个有返回值的方法,并且该返回值必须为K类型 
  110.      *  
  111.      * @param list 
  112.      *            待分组的列表 
  113.      * @param map 
  114.      *            存放分组后的map 
  115.      * @param method 
  116.      *            方法 
  117.      */  
  118.     @SuppressWarnings("unchecked")  
  119.     public static <K, V> void listGroup2Map(List<V> list, Map<K, List<V>> map, Method method) {  
  120.         // 入参非法行校验  
  121.         if (null == list || null == map || null == method) {  
  122.             System.out.print("CommonUtils.listGroup2Map 入参错误,list:" + list + " ;map:" + map + " ;method:" + method);  
  123.             return;  
  124.         }  
  125.   
  126.         try {  
  127.             // 开始分组  
  128.             Object key;  
  129.             List<V> listTmp;  
  130.             for (V val : list) {  
  131.                 key = method.invoke(val);  
  132.                 listTmp = map.get(key);  
  133.                 if (null == listTmp) {  
  134.                     listTmp = new ArrayList<V>();  
  135.                     map.put((K) key, listTmp);  
  136.                 }  
  137.                 listTmp.add(val);  
  138.             }  
  139.         } catch (Exception e) {  
  140.             System.out.print("分组失败!");  
  141.         }  
  142.     }  
  143.   
  144. }  



测试类

[java] view plain copy
  1. import java.util.ArrayList;  
  2. import java.util.LinkedHashMap;  
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import com.framework.common.CommonUtils.GroupBy;  
  7.   
  8. public class Test {  
  9.   
  10.     /** 
  11.      * @param args 
  12.      */  
  13.     public static void main(String[] args) {  
  14.         // 准备一个集合  
  15.   
  16.         final int loop = 1000 * 1000;  
  17.         List<Data> list = new ArrayList<Data>(); // size=8 * loop  
  18.         for (int i = 0; i < loop; i++) {  
  19.             list.add(new Data().setId(1L).setCourseId(200010L).setContent("AAA"));  
  20.             list.add(new Data().setId(2L).setCourseId(200010L).setContent("BBB"));  
  21.             list.add(new Data().setId(3L).setCourseId(200011L).setContent("CCC"));  
  22.             list.add(new Data().setId(4L).setCourseId(200011L).setContent("DDD"));  
  23.             list.add(new Data().setId(5L).setCourseId(200010L).setContent("EEE"));  
  24.             list.add(new Data().setId(6L).setCourseId(200011L).setContent("FFF"));  
  25.             list.add(new Data().setId(7L).setCourseId(200010L).setContent("GGG"));  
  26.             list.add(new Data().setId(8L).setCourseId(200012L).setContent("HHH"));  
  27.         }  
  28.         // 进行分组 1  
  29.         long time = System.currentTimeMillis();  
  30.         Map<Long, List<Data>> map2 = new LinkedHashMap<Long, List<Data>>();  
  31.         CommonUtils.listGroup2Map(list, map2, Data.class"getId");// 输入方法名  
  32.           
  33.         long duration = System.currentTimeMillis() - time;  
  34.   
  35.         System.out.println("分组一执行:" + duration + "毫秒!");  
  36.   
  37.         // 分组二  
  38.         time = System.currentTimeMillis();  
  39.         Map<Long, List<Data>> map = CommonUtils.group(list, new GroupBy<Long>() {  
  40.             @Override  
  41.             public Long groupby(Object obj) {  
  42.                 Data d = (Data) obj;  
  43.                 return d.getCourseId(); // 分组依据为课程ID  
  44.             }  
  45.         });  
  46.   
  47.         duration = System.currentTimeMillis() - time;  
  48.   
  49.         System.out.println("分组二执行:" + duration + "毫秒!");  
  50.   
  51.     }  
  52.   
  53. }  
阅读全文
0 0