java合并时间段

    public static List<TimeSlot> mergeTimeSlots(List<TimeSlot> timeSlots) {
        // 如果只剩一个时间段直接返回
        if (timeSlots.size() == 1) {
            return timeSlots;
        }
        for (int i = 0; i < timeSlots.size(); i++) {
            for (int j = i + 1; j < timeSlots.size(); j++) {
                TimeSlot timeSlot1 = timeSlots.get(i);
                TimeSlot timeSlot2 = timeSlots.get(j);
                List<TimeSlot> mergeSlot = mergeTwo(timeSlot1, timeSlot2);
                // 如果两个时间段能合并则递归继续合并
                if (mergeSlot.size() == 1) {
                    timeSlots.remove(timeSlot1);
                    timeSlots.remove(timeSlot2);
                    timeSlots.addAll(mergeSlot);
                    mergeTimeSlots(timeSlots);
                }
            }
        }
        return timeSlots;
    }

    private static List<TimeSlot> mergeTwo(TimeSlot timeSlot1, TimeSlot timeSlot2) {
        List<TimeSlot> result = new ArrayList<>();
        Date start1 = timeSlot1.getStartDate();
        Date start2 = timeSlot2.getStartDate();
        Date end1 = timeSlot1.getEndDate();
        Date end2 = timeSlot2.getEndDate();
        // 如果两个时间段完全没有交集则直接返回
        if (end1.before(start2) || start1.after(end2)) {
            result.add(timeSlot1);
            result.add(timeSlot2);
        }
        // 如果有完全包含则去掉小的那个
        else if (!start1.after(start2) && !end1.before(end2)) {
            result.add(timeSlot1);
        } else if (!start2.after(start1) && !end2.before(end1)) {
            result.add(timeSlot2);
        }
        // 有交集则合并
        else if (start1.before(start2) && end1.before(end2)) {
            timeSlot1.setEndDate(end2);
            result.add(timeSlot1);
        } else if (start2.before(start1) && end2.before(end1)) {
            timeSlot2.setEndDate(end1);
            result.add(timeSlot2);
        }
        return result;
    }

    private static class TimeSlot {
        private Date startDate;
        private Date endDate;

        public TimeSlot(Date startDate, Date endDate) {
            this.startDate = startDate;
            this.endDate = endDate;
        }

        public Date getStartDate() {
            return startDate;
        }

        public void setStartDate(Date startDate) {
            this.startDate = startDate;
        }

        public Date getEndDate() {
            return endDate;
        }

        public void setEndDate(Date endDate) {
            this.endDate = endDate;
        }
    }

 

posted @ 2022-04-25 14:20  一只韭菜  阅读(648)  评论(0编辑  收藏  举报