I am trying to reduce a stream of type Rectangle by doing this:
public static Optional<Rectangle> intersectAll(Stream<Rectangle> rectangles) {
return rectangles
.reduce((r1, r2) -> r1.intersection(r2));
The method intersection
takes one argument of type Rectangle
has return type Optional<Rectangle>
and returns a Optional.of(Rectangle)
if the two rectangles do intersect, and an Optional.empty()
if they do not.
I wish the stream to be reduced such that if one time the r1.intersection(r2)
lambda function returns an empty optional, the method intersectAll
returns an empty optional, and if r1.intersection(r2)
always returns a Rectangle, the output of intersectAll
would be the just the reduced Rectangle.
However, as you can probably see, reduce doesn't like this as the intersection method doesn't take in an Optional, so I'm asking if there is a way to 'break out' of the reduce when it hits an empty optional, so I can return an empty optional.