需求:
新增时间段字符串,时间段不能交叉(不能重叠)
已有时间段1=00:00-01:00
新增时间段2=00:30-02:00
则不能新增,两个时间段出现交叉部分。
正常效果如下图:
代码实现:
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<TimeInterval> timeIntervals = new ArrayList<>();
// 假设现有的时间段
timeIntervals.add(new TimeInterval("00:00", "02:00"));
timeIntervals.add(new TimeInterval("02:00", "05:00"));
// 新的时间段,想要插入
TimeInterval newTimeInterval = new TimeInterval("03:00", "06:00");
boolean canBeSaved = checkTimeInterval(timeIntervals, newTimeInterval);
if (!canBeSaved) {
System.out.println("时间有交叉,无法保存数据");
} else {
System.out.println("没有交叉时间,可以保存数据");
timeIntervals.add(newTimeInterval); // 如果没有交叉,将它添加到集合中
}
}
// 单独的方法,用于检查新时间段是否与现有的时间段集合有交叉
public static boolean checkTimeInterval(List<TimeInterval> timeIntervals, TimeInterval newTimeInterval) {
boolean isOverlap = timeIntervals.stream()
.anyMatch(timeInterval -> timeInterval.isOverlap(newTimeInterval));
return !isOverlap;
}
}
class TimeInterval {
private LocalTime start;
private LocalTime end;
public TimeInterval(String start, String end) {
this.start = LocalTime.parse(start);
this.end = LocalTime.parse(end);
}
public boolean isOverlap(TimeInterval other) {
return start.isBefore(other.end) && other.start.isBefore(end);
}
}