原时间段:08:00-10:00,17:00-18:00,09:00-13:00,12:00-15:00,17:00-18:00,09:00-13:00
处理后:08:00-15:00,17:00-18:00
*自动过滤无效时间段;
*时间格式自行校验;
public static void main(String[] args) {
String str = "08:00-10:00,17:00-18:00,09:00-13:00,12:00-15:00,17:00-18:00,09:00-13:00";
System.out.println(unRedoMergeTime(str));
}
public static String unRedoMergeTime(String str) {
// 去重
Set<String> set = new HashSet<>(Arrays.asList(str.split(",")));
// 排序
List<String> list = new ArrayList<>(set);
Collections.sort(list);
list.forEach(time -> {
System.out.println(time);
});
// 合并
List<String> newList = new ArrayList<>();
newList.add(list.get(0));
int len = list.size();
String swap = list.get(0);
for (int i = 1; i < len; i++) {
swap = mySplit(newList, swap, list.get(i));
}
// 还原String
return String.join(",", newList);
}
public static String mySplit(List<String> newList, String tim1, String tim2) {
int s1 = Integer.parseInt(tim1.split("-")[0].replace(":", ""));
int e1 = Integer.parseInt(tim1.split("-")[1].replace(":", ""));
int s2 = Integer.parseInt(tim2.split("-")[0].replace(":", ""));
int e2 = Integer.parseInt(tim2.split("-")[1].replace(":", ""));
// 过滤无效时间段(起始时间大于结束时间)
if (newList.size() == 1 && s1 > e1) {
newList.remove(tim1);
newList.add(tim2);
return newList.get(newList.size() - 1);
}
if (s2 > e2)
return newList.get(newList.size() - 1);
if (s2 > e1) {
newList.add(tim2);
} else if (s2 <= e1) {
if (e2 >= e1) {
newList.remove(tim1);
newList.add(tim1.split("-")[0] + "-" + tim2.split("-")[1]);
}
}
return newList.get(newList.size() - 1);
}
输出:
08:00-10:00,17:00-18:00,09:00-13:00,12:00-15:00,17:00-18:00,09:00-13:00
08:00-15:00,17:00-18:00