您的位置:首页 > 其它

将两个List根据某个相同字段来进行合并,排序

2016-11-14 12:12 706 查看
业务类简介:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐