java实现多个时间段合并
如题,将多个时间段进行合并
参考力扣合并区间写法
private static List<ProductStartWork> mergeOverlappingTimePeriods(List<ProductStartWork> timePeriods) {List<ProductStartWork> mergedIntervals = new ArrayList<>();if (timePeriods == null || timePeriods.size() == 0) {return mergedIntervals;}// 按照起始时间排序timePeriods.sort(Comparator.comparingLong(interval -> interval.getStartDate().getTime()));// 遍历时间段并合并重叠部分ProductStartWork currentInterval = timePeriods.get(0);for (int i = 1; i < timePeriods.size(); i++) {ProductStartWork nextInterval = timePeriods.get(i);// 如果有重叠部分,则合并时间段if (currentInterval.getEndDate().getTime() >= nextInterval.getStartDate().getTime()) {long time1 = currentInterval.getEndDate().getTime();long time2 = nextInterval.getEndDate().getTime();if (time1 > time2) {currentInterval.setEndDate(currentInterval.getEndDate());} else {currentInterval.setEndDate(nextInterval.getEndDate());}} else {mergedIntervals.add(currentInterval);currentInterval = nextInterval;}}// 添加最后一个时间段mergedIntervals.add(currentInterval);return mergedIntervals;}
为了方便直接排序,将时间转为了时间戳进行操作