一个日期时间段有交集求并集的问题

时间:2020-11-29 14:00:23
同学工作中遇到的,问题大概是:输入一系列时间段(开始日期start,结束日期end)返回结果为:时间段若有交集则取其并集,无交集则返回原时间段,如输入:20160101,20160103;20160102,20160105;20160109,20160110;20160110,20160110;
则返回:20160101,20160105;20160109,20160110;
在这里我将输入的格式定为20160101,20160120格式代表开始和结束日期,并将其封装到Single对象中,对single对象初排序sort;然后再取并集,代码如下:
package jsoup;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class Merge20170108 {
public static void main(String[] args) throws IOException{
List<Single> list = new LinkedList<Single>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
while(input != null && ! input.equals("stop")){ // 若输入stop则停止向list中add操作
list.add(new Single(new String[]{input.substring(0, input.indexOf(",")),input.substring(input.indexOf(",")+1)})); //将输入的20160101,20160104格式的字符串保存在Single對象中
input = br.readLine();
}
merge(list);
br.close();


}
//对已经用开始日期start初排序的list进行交集合并处理
public static void merge(List<Single> list){
Collections.sort(list, new Comparator());

for(int i =0; i<list.size()-1; i++){
Single outer;
Single inner;
for(int j =i+1; j<list.size(); j++){
outer = list.get(i);
inner = list.get(j);
String start = outer.start;
String end = outer.end;
String start2 = inner.start;
String end2 = inner.end;
if(end.compareTo(start2)>=0 && end.compareTo(end2)<=0){
outer.end = end2;
list.set(i, outer);
list.remove(j);
j--;
}
else if(end.compareTo(end2)>=0 || start.compareTo(end2)==0){
list.remove(j);
j--;
}
}
}
for(Single single : list) //輸出操作
System.out.println(single);
}
}

//存放输入的开始日期和结束日期的对象
class Single {
String start;
String end;
public Single(String[] str){
start = str[0];
end = str[1];
}

public String toString(){ //重写Single对象的toString方法
return start +"," + end;
}
}
//Single的比较器,比较两个Single对象的开始日期,从而从小到大排序
class Comparator implements java.util.Comparator<Single> {

@Override
public int compare(Single o1, Single o2) {
return o1.start.compareTo(o2.start)>0? 1:-1;
}

}