I have a bunch of Joda time Interval objects stored in a List. All of these Intervals have valid start and end instants. These Intervals can have any overlaps, abuts or even gaps among themselves.
I want to flatten (optimize) these Intervals to the maximum possible. I mean, I have to generate other Interval objets that will represent the very same from – to information, but without redundancy.
For example:
I1: 2012-01-12T05:00:00.000/2013-03-18T14:00:00.000
I2: 2012-04-12T04:00:00.000/2013-02-10T06:00:00.000
I3: 2015-12-12T04:00:00.000/2016-12-12T06:00:00.000
Should produce:
I1_o: 2012-01-12T05:00:00.000/2013-03-18T14:00:00.000
I2_o: 2015-12-12T04:00:00.000/2016-12-12T06:00:00.000
(I2 is absolutely within I1, so can be ignored, and the resulted two has a gap).
I know the three methods in Interval class that can help me, but I guess I need a more generic algorithm that can search overlaps between some kind of intervals, like ordinary numbers, etc.
Thanks in advance!
Sort the intervals by start time and loop through the intervals. If the start time of interval i is less than or equal to the end time of interval i-1, they can be merged into one interval whose end time is the greatest end time of the two original intervals. (Put the resulting intervals into a new list so that you can safely loop through the sorted list of original intervals without modifying it.)