我正在尝试通过这样做来减少类型为Rectangle的流:
public static Optional<Rectangle> intersectAll(Stream<Rectangle> rectangles) {
return rectangles
.reduce((r1, r2) -> r1.intersection(r2));方法intersection接受一个类型为Rectangle的参数,返回类型为Optional<Rectangle>,如果两个矩形相交,则返回Optional.of(Rectangle),如果不相交,则返回Optional.empty()。
我希望减少流,如果有一次r1.intersection(r2) lambda函数返回一个空可选,方法intersectAll返回一个空可选,如果r1.intersection(r2)总是返回一个矩形,intersectAll的输出将只是减少的矩形。
但是,正如您可能看到的,reduce并不喜欢这种情况,因为交集方法不接受Optional,所以我想知道当reduce遇到空optional时,是否有办法“中断”reduce,这样我就可以返回一个空optional。
发布于 2021-04-16 04:25:34
不能中断减少终端操作。但是,在某些情况下,您可以使用filter, takewhile, findFirst和类似的运算符来实现此目标。
发布于 2021-04-16 05:06:23
我相信可以找到解决方案,但我建议不要使用流。
在我看来,矩形的交集并不适合于reduce操作。它没有身份。您还需要一个组合器(参见Stream类中reduce方法的其他方法签名)并适当地实现它。
身份是一种值,因此value op identity == value -尝试找到这样的交集通常是不会的,这可能就是你想要突破的原因。也许试着把它看作是一个提示,你想要走的路并不是很美。
至于组合器,你需要考虑如何组合结果--这可能并不太难。尽管如此,我还是觉得这不是一条正确的道路。
试着想象一下你正在尝试做什么。前两行的外观表明它不适合。因为没有身份可以使用,所以没有意义(Empty intersect Rectangle results in Empty,这不是身份)
R1 intersect R2 intersect R3 intersect R4
Optional<Ra> intersect R3 intersect R4
Optional<Rb> intersect R4
Optional<Rc>你可以用传统的方式来做这件事吗?您可以更容易地跳出循环。它的可读性也会更好。
https://stackoverflow.com/questions/67115194
复制相似问题