Arnaud Denoyelle Arnaud Denoyelle - 9 days ago 9
Java Question

Merge ranges with guava

I need to merge some ranges.

I discovered guava and see that it can handle it in some cases.

RangeSet<Integer> rangeSet = TreeRangeSet.create();
rangeSet.add(Range.closed(1, 10)); // {[1, 10]}
rangeSet.add(Range.closed(8, 15)); // {[1, 15]}


Now, I need to tell Guava that I need that
[1, 10] + [11, 20] = {[1, 20]}
 and not
{[1, 10], [11, 20]}
.

Is there an option somewhere for this?

Answer

If you want ranges like this to be merged, you need to canonicalize them first:

rangeSet.add(Range.closed(1, 10).canonical(DiscreteDomain.integers()); 
// {[1, 11)}
rangeSet.add(Range.closed(11, 20).canonical(DiscreteDomain.integers());
// {[1, 21)}