编程语言
首页 > 编程语言> > java合并时间段去重

java合并时间段去重

作者:互联网

合并时间段去重

先做排序,后判断时间交叉,合并时间段去重

代码如下

/**
     * 合并去重时间段
     *
     * @return
     */
    public static List<Map<String, Date>> getTimePeriodListDumplictcatePeriod(List<Map<String, Date>> periodList) {
        List<Map<String, Date>> result = new ArrayList<>();
        //列表不能为空
        if (periodList == null) {
            return null;
        }
        //对数据排序,开始时间从小到大
        Collections.sort(periodList, new Comparator<Map<String, Date>>() {
            @Override
            public int compare(Map<String, Date> u1, Map<String, Date> u2) {
                long diff = u1.get("startDate").getTime() - u2.get("startDate").getTime();
                if (diff > 0) {
                    return 1;
                } else if (diff < 0) {
                    return -1;
                }
                return 0; //相等为0
            }

        });

        for (int i = 0; i < periodList.size() - 1; i++) {
            int j = i + 1;
            //判断 i的Endtime 与j 的Begintime 是否有交叉,有交叉,更新 j的Begintime 为i的Begintime, 并移除i
            if (periodList.get(i).get("endDate").after(periodList.get(i).get("startDate"))) {
                periodList.get(j).put("startDate", periodList.get(i).get("startDate"));
                periodList.remove(i);
                i--;
            }
        }

        result = periodList;
        return result;
    }

标签:startDate,return,get,int,合并,时间段,periodList,java
来源: https://blog.csdn.net/gsls200808/article/details/122146061