本文主要是介绍求时间段并集,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
区间类
@Setter
@Getter
public class TimeZone {/** 起始时间 */private String startTime;/** 终止时间 */private String endTime;}
合并方法
public List<TimeZone> getTimeZoneUnion(List<TimeZone> timeZoneList) {List<TimeZone> mergeTimeZoneList = new ArrayList<>();List<TimeZone> lastTimeZoneList = timeZoneList;int lastSize = lastTimeZoneList.size();int mergeSize = mergeTimeZoneList.size();// 防止死循环int count = 0;while ((lastSize != mergeSize) || count > 50) {lastTimeZoneList = mergeTimeZone(lastTimeZoneList);lastSize = lastTimeZoneList.size();mergeTimeZoneList = mergeTimeZone(lastTimeZoneList);mergeSize = mergeTimeZoneList.size();count++;}return mergeTimeZoneList;}private List<TimeZone> mergeTimeZone(List<TimeZone> timeZoneList){try {HashMap<Date, Date> dateMap = new HashMap<>(16);SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");for (TimeZone timeZone : timeZoneList) {Date startTime = dateFormat.parse(timeZone.getStartTime());Date endTime = dateFormat.parse(timeZone.getEndTime());//第一个时间if (MapUtils.isEmpty(dateMap)) {dateMap.put(startTime, endTime);} else {List<Date> dateList = new ArrayList<>(dateMap.keySet());for (int i = 0; i < dateList.size(); i++) {Date start = dateList.get(i);Date end = dateMap.get(start);if(end != null){if ((startTime.before(start) || startTime.equals(start))&& (endTime.after(start) || endTime.equals(start))&& (endTime.before(end) || endTime.equals(end))) {// 起点早于该区间 终点属于该区间dateMap.remove(start);dateMap.put(startTime, end);} else if ((startTime.before(start) || startTime.equals(start))&& (endTime.after(end) || endTime.equals(end))) {// 起点早于该区间 终点晚于该区间dateMap.remove(start);dateMap.put(startTime, endTime);} else if ((endTime.after(end) || endTime.equals(end))&& (startTime.after(start) || startTime.equals(start))&& (startTime.before(end) || startTime.equals(end))) {// 终点晚于该区间 起点属于该区间dateMap.put(start, endTime);} else if (endTime.before(start) || startTime.after(end)) {if (i == dateList.size() - 1) {// 遍历完也没有重合的区间就加入dateMap.put(startTime, endTime);}}}}}}List<TimeZone> newTimeZoneList = new ArrayList<>();List<Date> dateList = CollectionUtil.sort(new ArrayList<>(dateMap.keySet()), (o1, o2) -> o1.getTime() >= o2.getTime() ? 1 : -1);for (Date date : dateList) {TimeZone timeZone = new TimeZone();timeZone.setStartTime(dateFormat.format(date));timeZone.setEndTime(dateFormat.format(dateMap.get(date)));newTimeZoneList.add(timeZone);}return newTimeZoneList;} catch (Exception e) {throw new RuntimeException(e);}}
这篇关于求时间段并集的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!