Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract gaps from a List of Range<Date>

I have a list of Range<Date> based on the Guava library, they never overlap.

  • 2001-01-10 2001-01-15
  • 2001-01-20 2001-01-22
  • 2001-01-28 2001-01-29

Then, I have a reference range:

  • 2001-01-01 2001-01-31

I want to find all the exclusive gaps between the list and the reference range:

  • 2001-01-01 2001-01-10
  • 2001-01-15 2001-01-20
  • 2001-01-22 2001-01-28
  • 2001-01-29 2001-01-31

For this example, the Date objects are simple, but in reality they may vary in format depending on their ChronoUnit.

Is there a right way to get this result without too much coding?

like image 887
Guillaume F. Avatar asked Sep 02 '25 04:09

Guillaume F.


1 Answers

My approach would be something like

RangeSet<Date> rangeSet = TreeRangeSet.create();
rangeSet.add(referenceRange);
for (Range<Date> range : rangesToRemove) {
  rangeSet.remove(range);
}
for (Range<Date> exclusiveRange : rangeSet.asRanges()) {
   ...
}

If you manipulate the range bounds correctly, you should get them in the format you desire.

like image 112
Louis Wasserman Avatar answered Sep 05 '25 01:09

Louis Wasserman