Suppose I have a list of intervals (sorted by start) and I want to break them up so that I have a list of overlapping groups of intervals. So, for example, with Interval as:
public class Interval {
private final int start;
private final int end;
public Interval(int start,int end){
this.start = start;
this.end = end;
}
public int getStart(){return start;}
public int getEnd(){return end;}
public String toString(){ return "("+start+","+end+")"; }
}
And a List<Interval> like:
[(0,4),(1,7),(6,10),(13,17),(20,100),(22,31),(60,65)]
I want an output of List<List<Interval>>:
[[(0,4),(1,7),(6,10)],[(13,17)],[(20,100),(22,31),(60,65)]]
I can code this up, but I'm really enjoying the more functional approach of Java 8, and want to know if there is anything like an idiomatic way to do this using Java 8 streams.
I've had a look at the "group by" styles of provided Collectors, but they don't seem to apply since I'm not really grouping by a classifier- you can't compute the groups based only on a property of each individual element, you have to consider the properties of each element in relation to the groups that have been computed so far.
Certainly there is non-crazy way to do this in functional languages (though I speak as someone who isn't really a functional programmer :-) ). How can I do it with streams in Java 8?