1. 程式人生 > >對集合中的物件分組,並排序

對集合中的物件分組,並排序

// 資料來源
List<ReportStatisticsAgentInfo> list = reportReceiveTaskMapper.getResourceAgentReportTypequarter(param);
if(null==list || list.size()==0){
return result;
}
// 定義一個map 用於分組
Map<String, List<ReportStatisticsAgentInfo>> mapList = new HashMap<String, List<ReportStatisticsAgentInfo>>();
// 遍歷集合以AgentId為鍵,map.get(key)為值儲存到集合中
for (Iterator it = list.iterator(); it.hasNext();) {
// 將迴圈讀取的結果放入物件中
ReportStatisticsAgentInfo rsai = (ReportStatisticsAgentInfo) it.next();
// 如果在這個map中包含有相同的鍵,這建立一個集合將其存起來
if (mapList.containsKey(rsai.getAgentId())) {
List<ReportStatisticsAgentInfo> syn = mapList.get(rsai.getAgentId());
syn.add(rsai);
// 如果沒有包含相同的鍵,在建立一個集合儲存資料
} else {
List<ReportStatisticsAgentInfo> syns = new ArrayList<ReportStatisticsAgentInfo>();
syns.add(rsai);
mapList.put(rsai.getAgentId(), syns);
}
}
/**
 * 遍歷Map<String, List<ReportStatisticsAgentInfo>> mapList
 * 獲取每一個List<ReportStatisticsAgentInfo>
 * 對List<ReportStatisticsAgentInfo>中的元素按照時間排序
 */
for (Map.Entry<String, List<ReportStatisticsAgentInfo>> m : mapList.entrySet()) {
List<ReportStatisticsAgentInfo> rslist = m.getValue();
int tot = 0;
Collections.sort(rslist, new Comparator<ReportStatisticsAgentInfo>() {
@Override
public int compare(ReportStatisticsAgentInfo o1, ReportStatisticsAgentInfo o2) {
/*Long i = o1.getDayTime().getTime() - o2.getDayTime().getTime();*/
String[] s1 = o1.getStrDayTime().split("-");
int l1 = s1.length;
String[] s2 = o1.getStrDayTime().split("-");
int l2 = s2.length;
int i = Integer.parseInt(s1[l1-1])-Integer.parseInt(s2[l2-1]);
if (i > 0) {
return 1;
} else if (i < 0) {
return -1;
} else {
return 0;
}
}
});