/** * Find all the interval overlaps between two collections of intervals. * <p> * If the left set is null, return the right. This makes this usable in a reduce function. * * @param left The intervals being streamed over * @param right The intervals being tested against * * @return A set of intervals describing the time common to both sets */ public static Set<Interval> getOverlappingSubintervals(Collection<Interval> left, Collection<Interval> right) { if (left == null) { return new LinkedHashSet<>(right); } // Each interval in left is matched against all intervals in the right, collecting overlaps return left.stream() .flatMap(leftElement -> getIntervalOverlaps(leftElement, right)) .collect(Collectors.toSet()); }