將兩個List根據某個相同欄位來進行合併,排序
業務類簡介:
public class ChannelSituation implements Serializable {
private Long id;
private Date date;//日期
private Integer identityCount;//認證人數
private Integer registCount; //註冊人數
private Integer investCount;//投資人數
}
注:三個欄位的關係:註冊-> 認證 ->投資
identityCountList 中的資料只有認證人數:{(1,“2016-10-09”,3,0,0),(2,“2016-10-11”,5,0,0),(3,“2016-11-15”,2,0,0)}
registAndInvestCountList 中的資料有註冊和投資人數:{(1,“2016-10-03”,0,3,0),(1,“2016-10-09”,0,8,3),(2,“2016-10-11”,0,10,4),(3,“2016-11-15”,0,5 , 0)}
// 儲存有日期和認證人數
List identityCountList ;
// 儲存有日期和註冊人數、投資人數
List registAndInvestCountList ;
現在要將兩個List資料合併如下:
合併
for (ChannelSituation identityCount : identityCountList) {
boolean flag = false;
for (ChannelSituation registAndInvestCount : registAndInvestCountList) {
if (identityCount.getDate().getTime() == registAndInvestCount.getDate().getTime()) {
registAndInvestCount.setIdentityCount(identityCount.getIdentityCount());
flag = true;
break;
}
}
if (!flag) {
registAndInvestCountList.add(identityCount);
}
}
合併之後registAndInvestCountList資料變成認證,註冊,投資人數都有,日期無重複。
排序
首先重寫Comparator方法:
public class MyComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
ChannelSituation c1 = (ChannelSituation) o1;
ChannelSituation c2 = (ChannelSituation) o2;
if (c1.getDate().getTime() < c2.getDate().getTime()) {// 根據時間排序,這裡根據你的需要來重寫
return 1;
} else {
return 0;
}
}
}
然後排序:
public static List<ChannelSituation> sortList(List<ChannelSituation> channelSituationList) {
MyComparator mc = new MyComparator();
int len = channelSituationList.size();
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
if (mc.compare(channelSituationList.get(i), channelSituationList.get(j)) == 1) {
Collections.swap(channelSituationList, i, j);
}
}
}
return channelSituationList;
}
最後,下一篇寫一個通用的根據List指定欄位排序的工具類ListSortUtil