Guillaume F.
Guillaume F.

Reputation: 6473

Extract gaps from a List of Range<Date>

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

Then, I have a reference range:

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

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?

Upvotes: 4

Views: 1666

Answers (2)

mfulton26
mfulton26

Reputation: 31234

You can create/build a RangeSet from your list of Range<Date> and use its complement() with subRangeSet(Range) to get the exclusive gaps in your reference range:

RangeSet<Date> exclusiveRangeSet = rangeSet.complement().subRangeSet(referenceRange);

Upvotes: 4

Louis Wasserman
Louis Wasserman

Reputation: 198093

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.

Upvotes: 4

Related Questions