[英]What is a good way to implement the equivalent of Haskell's “or” function using Streams in Java
我正在寻找使用Streams在Java中等效于Haskell的“或”函数 。
当提供无限流时,此版本不返回:
public static Boolean or(Stream<Boolean> bs) {
return bs.reduce(false, (x, y) -> x || y);
}
由于bs流已使用两次,因此该版本无法运行:
public static Boolean or(Stream<Boolean> bs) {
Optional<Boolean> b0 = bs.findFirst();
if (b0.isPresent()) {
return b0.get() || or(bs.skip(1));
} else {
return false;
}
}
我是Java的新手,所以任何提示都将不胜感激。 谢谢。
只需将Stream#anyMatch(...)
与带返回值本身的Predicate
一起使用即可。
// assuming there are no null values
boolean or = booleans.anyMatch(b -> b); // will only match if value is true
与Haskell文档中描述or
链接的内容类似,如果Stream
是无限的,则它不能返回false
。 如果看到的只是false
值,它将继续消耗Stream
。
这是短路操作。 一旦找到true
值,它将(实际上,但不是必须)返回true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.