I have a list of LocalDates lets say 14-06-2020, 15-06-2020, 17-06-2020, 19-06-2020, 20-06-2020, 21-06-2020 and I want to have all consecutive intervals from above dates. So the output would be like
Interval 1 = [14-06-2020, 15-06-2020]
Interval 2 = [17-06-2020, 17-06-2020]
Interval 3 = [19-06-2020, 21-06-2020]
What would be the most efficient way to do in Java
So I have create an Interval class that would hold start and enddate
public class Interval{
private LocalDate startDate;
private LocalDate endDate;
}
I can iterate over each element in list of dates and then check for logic if two dates are consecutive something in below line,
public static void main(String args[]){
List<LocalDate> dates = new ArrayList<>();
dates.add(LocalDate.of(2020,6,14));
dates.add(LocalDate.of(2020,6,15));
dates.add(LocalDate.of(2020,6,17));
dates.add(LocalDate.of(2020,6,19));
dates.add(LocalDate.of(2020,6,21));
dates.add(LocalDate.of(2020,6,20));
Collections.sort(dates);
//Handle if empty or null
List<Interval> intervals = new ArrayList<>();
if(dates==null || dates.size()==0){
throw new IllegalArgumentException("list cannot be empty");
}
//If only one date then the interval starts and ends with same date
if(dates.size()==1){
Interval interval = new Interval();
interval.setStartDate(dates.get(0));
interval.setEndDate(dates.get(0));
}
LocalDate firstDate = dates.get(0);
for(int i =1;i<dates.size(); i++){
LocalDate endDate = dates.get(i);
LocalDate nextDate = endDate.plusDays(1);
//iterate over to get the desired list of interval
while(my condition satisfies){
//create new interval
}
//intervals.add(interval
}
}
I wanted to check if there is something better using stream api or can i group dates by consecutive days and then collect them using interval