Reputation: 11427
I have to handle a list of timestamps (Long
) in a Java 8 application:
If a user adds a new range, it should be merged together with the other existing ranges, like in this pseudo code:
rangeList = [100, 200], [300, 400], [500, 600], [700, 800]
newRangeList = rangeList.add([150, 550])
println(newRangeList) // Expected output: [100, 600], [700, 800]
I tried using a List
of Google Guava Range class but merging together new timestamp ranges gets surprisingly complicated.
Using the new LongStream from Java 8 instead of the Range class doesn't helped me.
I think an Interval Tree would be a good data structure to handle merging efficient, but I found no library which is implementing this.
Is there a library for handling numeric ranges and merging?
Upvotes: 0
Views: 592
Reputation: 121702
From what you want to achieve, and since you mention using Guava's Range, Guava already has what you want: a RangeSet
.
The javadoc for this interface specifies that:
[...]Implementations that choose to support the add(Range) operation are required to ignore empty ranges and coalesce connected ranges.
It is an interface; you probably want to use a TreeRangeSet
for your purposes:
// for whatever type C...
final RangeSet<C> rangeSet = TreeRangeSet.create();
Upvotes: 4