在一些應用中,需要將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);
}
});