将两个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

猜你喜欢

转载自blog.csdn.net/innerpeaceScorpio/article/details/53157729
今日推荐