如果您只关心日期(不关心时间),则最好使用LocalDate
。其次,我假设您有一个任务构造函数。因此,我使用了以下Task
对象:
static class Task {
LocalDate start;
LocalDate end;
Set<String> actionItems;
public Task(LocalDate start, LocalDate end,
Collection<String> actionItems) {
this.start = start;
this.end = end;
this.actionItems = new HashSet<>(actionItems);
}
@Override
public String toString() {
return start + ".." + end + ": "+actionItems;
}
}
这里是更一般任务的解决方案,它根据您的规则(输入集合不一定排序)合并给定集合中的所有任务:
public static List<Task> convert(Collection<Task> input) {
NavigableMap<LocalDate, Set<String>> map = new TreeMap<>();
map.put(LocalDate.MIN, new HashSet<>());
for (Task task : input) {
if (!map.containsKey(task.start)) {
map.put(task.start, new HashSet<>(map.lowerEntry(task.start).getValue()));
}
if (!map.containsKey(task.end)) {
map.put(task.end, new HashSet<>(map.lowerEntry(task.end).getValue()));
}
for (Set<String> set : map.subMap(task.start, task.end).values()) {
set.addAll(task.actionItems);
}
}
List<Task> result = new ArrayList<>();
LocalDate prev = null;
Set<String> prevValues = Collections.emptySet();
for (Entry<LocalDate, Set<String>> entry : map.entrySet()) {
if (!prevValues.isEmpty()) {
result.add(new Task(prev, entry.getKey(), prevValues));
}
prev = entry.getKey();
prevValues = entry.getValue();
}
return result;
}
核心是 NavigableMap
,其中每个键表示下一个时间段的开始,值是从给定开始到下一个键的期间的操作集合(空值对应没有操作的期间)。在添加新任务时,现有条目将相应更新。使用示例:
List<Task> res = convert(Arrays.asList(
new Task(LocalDate.parse("2015-01-01"), LocalDate.parse("2015-01-31"),
Arrays.asList("A", "B")),
new Task(LocalDate.parse("2014-01-01"), LocalDate.parse("2014-01-31"),
Arrays.asList("A", "B")),
new Task(LocalDate.parse("2015-01-15"), LocalDate.parse("2015-02-15"),
Arrays.asList("C"))));
res.stream().forEach(System.out::println);
输出:
2014-01-01..2014-01-31: [A, B]
2015-01-01..2015-01-15: [A, B]
2015-01-15..2015-01-31: [A, B, C]
2015-01-31..2015-02-15: [C]
LocalDateTime
,它将以相同的方式工作,只需在所有地方替换类名即可。我添加了一个不重叠的任务(2014年的任务)来测试它是否被正确处理。删除它,输出将保持不变。 - Tagir Valeev