Reputation: 6473
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?
Upvotes: 4
Views: 1666
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
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