com.nls.util.RangeSet Maven / Gradle / Ivy
package com.nls.util;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class RangeSet> {
private final Set> ranges = new TreeSet<>();
public RangeSet() {
}
public RangeSet(Collection> ranges) {
for (Range range : ranges) {
add(range);
}
}
public boolean contains(T element) {
return getContainingRange(element).isPresent();
}
public Optional> getContainingRange(T element) {
return ranges.stream().filter(r -> r.containsValue(element)).findAny();
}
public Set> getRanges() {
return ranges;
}
public void add(Range range) {
Set> matches = ranges.stream().filter(r -> r.intersects(range)).collect(Collectors.toSet());
ranges.removeAll(matches);
Range merged = range;
for (Range match : matches) {
merged = range.merge(match);
}
ranges.add(merged);
}
public RangeSet merge(RangeSet graph) {
RangeSet merge = make();
merge.ranges.addAll(ranges);
for (Range range : graph.ranges) {
merge.add(range);
}
return merge;
}
protected RangeSet make() {
return new RangeSet<>();
}
}