Library for handling a List of Ranges

孤者浪人 提交于 2019-12-12 02:50:05

问题


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?


回答1:


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();


来源:https://stackoverflow.com/questions/26586441/library-for-handling-a-list-of-ranges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!