java List分组和排序处理

在一些应用中,需要将List中的对象按某种情况分组或者排序处理。做个小结如下:

1.       如一个List中存放了ProductDoing对象,productDoing对象有rawTypeId 现在要求将rawTypeId分组处理。

先用Map找出list中所有的分组:

//原料类型组

Map<Integer,String> groups = new HashMap<Integer,String>();

for(ProductDoingVo pd : products){

       groups.put(pd.getRawTypeId(),"");//这里并没有将该组的数据存入,看自己的需求吧

}

接下来就可以对已知的分组处理。

for(Integer rawTypeId : groups.keySet()){

for(ProductDoingVo pd : products){

   if(rawTypeId.equals(pd.getRawTypeId())){

              //处理该组的数据

     }

}

}

2.    如2个List中存放了map<String,String>对象, 一个map是一个条数据库表记录,key是数据库表中的字段名,value是字段对应的值, map中操作时间的key_value, 需要将这2个List合并之后按map中的操作时间去排个序。。。。

//先用addAll将list连接起来,合成一个List

List result = new ArrayList();  

Collections.addAll(result, a);//假设a b即为那两个list  

Collections.addAll(result, b); 

//实现一个Comparator就好了,根据map中的操作时间来排序

   Collections.sort(result, new Comparator<Map>()  

      {  

            public int compare(Map o1, Map o2) {  

               Date date1 = (Date)o1.get("trackdatetime");  

               Date date2 = (Date)o2.get("trackdatetime");  

              return date1.compareTo(date2);  

          }  

});