![[Java] 取多个时间段内的重叠时间部分 日期类型使用yyyyMMddHHmmss的Long类型(20220513104000),第1张 [Java] 取多个时间段内的重叠时间部分 日期类型使用yyyyMMddHHmmss的Long类型(20220513104000),第1张](/aiimages/%5BJava%5D+%E5%8F%96%E5%A4%9A%E4%B8%AA%E6%97%B6%E9%97%B4%E6%AE%B5%E5%86%85%E7%9A%84%E9%87%8D%E5%8F%A0%E6%97%B6%E9%97%B4%E9%83%A8%E5%88%86+%E6%97%A5%E6%9C%9F%E7%B1%BB%E5%9E%8B%E4%BD%BF%E7%94%A8yyyyMMddHHmmss%E7%9A%84Long%E7%B1%BB%E5%9E%8B%EF%BC%8820220513104000%EF%BC%89.png)
流程/思路:
package controller;
import java.util.*;
import java.util.stream.Collectors;
public class TestController {
/**
* @param unusableTimeList 所有时间段:[startTime, endTime, startTime, endTime, startTime, endTime]
* @return 返回时间段:[startTime, endTime, startTime, endTime]
*/
public static List<Long> getOverlapTimeRange(List<Long> unusableTimeList) {
List<Long> finalUnusableTimeList = new ArrayList<>();
// 统计时间段,去重
Map<List<Long>, Integer> timeRangeMap = new HashMap<>();
// 获取每段时间的时间点,去重
Set<Long> timeSet = new HashSet<>(unusableTimeList);
// 将Set转换为List, 并排序
List<Long> newUnusableTimeList = new ArrayList<>(timeSet).stream().sorted(Long::compareTo).collect(Collectors.toList());
// 统计每段时间的重复次数
Map<String, Integer> timeRangeReserCountMap = new HashMap<>();
for (int i = 0; i < newUnusableTimeList.size(); i++) {
if (i + 1 == newUnusableTimeList.size()) break;
// 每段时间的间隔
Long startInt = newUnusableTimeList.get(i);
Long endInt = newUnusableTimeList.get(i + 1);
String key = startInt + "_" + endInt;
// 每段时间的重复次数
Integer timeRangeCount = timeRangeReserCountMap.get(key) != null ? timeRangeReserCountMap.get(key) : 0;
//迭代每段时间范围,算出每子时间段内的重复时间占用数量
for (int j = 0; j < unusableTimeList.size(); j = j + 2) {
if (j + 1 == unusableTimeList.size()) break;
//预约开始结束范围
Long reserStartInt = unusableTimeList.get(j);
Long reserEndInt = unusableTimeList.get(j + 1);
if (reserStartInt <= startInt && endInt <= reserEndInt) {
timeRangeCount++;
}
if (timeRangeReserCountMap.get(key) != null && timeRangeReserCountMap.get(key) > 1) { // 判断该时间段是否达到某种需求条件,这里为时间段重复次数大于1的就返回
timeRangeMap.put(Arrays.asList(startInt, endInt), timeRangeCount);
}
timeRangeReserCountMap.put(key, timeRangeCount);
}
}
for (Map.Entry<List<Long>, Integer> entry : timeRangeMap.entrySet()) {
finalUnusableTimeList.addAll(entry.getKey());
}
return finalUnusableTimeList;
}
public static void main(String[] args) {
List<Long> unusableTimeList = new ArrayList<>();
unusableTimeList.add(20200513000000L);
unusableTimeList.add(20200513235959L);
unusableTimeList.add(20200513120000L);
unusableTimeList.add(20200513235959L);
unusableTimeList.add(20200513101010L);
unusableTimeList.add(20200513111111L);
unusableTimeList.add(20200513131313L);
unusableTimeList.add(20200513151515L);
List<Long> overlapTimeRange = getOverlapTimeRange(unusableTimeList);
System.out.println(overlapTimeRange);
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)