Getting list of all consecutive intervals from series of dates in Java
A "workaround" towards an approach based on Stream
upon the sorted collection could be to use markers for range lookup -
List<Integer> rangeMarkers = new ArrayList<>();
rangeMarkers.add(0);
rangeMarkers.addAll(IntStream.range(0, dates.size() - 1)
.filter(i -> !dates.get(i).plusDays(1).equals(dates.get(i + 1)))
.mapToObj(i -> i + 1)
.collect(Collectors.toList()));
rangeMarkers.add(dates.size());
System.out.println(rangeMarkers);
and then use those markers to map dates to Interval
-
List<Interval> intervals = IntStream.range(0, rangeMarkers.size() - 1)
.mapToObj(i -> new Interval(dates.get(rangeMarkers.get(i)),
dates.get(rangeMarkers.get(i + 1) - 1)))
.collect(Collectors.toList());
System.out.println(intervals);