简体   繁体   English

用Java中的Streams实现与Haskell的“或”函数等效的好方法是什么

[英]What is a good way to implement the equivalent of Haskell's “or” function using Streams in Java

I'm looking for an equivalent to Haskell's "or" function in Java using Streams. 我正在寻找使用Streams在Java中等效于Haskell的“或”函数

This version does not return when given an infinite stream: 当提供无限流时,此版本不返回:

    public static Boolean or(Stream<Boolean> bs) {
      return bs.reduce(false, (x, y) -> x || y);
    }

This version does not run because the bs stream is used twice: 由于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;
    }
}

I'm new to Java, so any tips would be greatly appreciated. 我是Java的新手,所以任何提示都将不胜感激。 Thanks. 谢谢。

Just use Stream#anyMatch(...) with a Predicate that returns the value itself. 只需将Stream#anyMatch(...)与带返回值本身的Predicate一起使用即可。

// assuming there are no null values
boolean or = booleans.anyMatch(b -> b); // will only match if value is true

Similarly to what is described in the Haskell documentation for or that you linked, if the Stream is infinite, it cannot return false . 与Haskell文档中描述or链接的内容类似,如果Stream是无限的,则它不能返回false It will continue to consume the Stream if all it sees is false values. 如果看到的只是false值,它将继续消耗Stream

This is a short-circuiting operation. 这是短路操作。 It will (actually, it can, but doesn't have to) return true as soon as it finds a true value. 一旦找到true值,它将(实际上,但不是必须)返回true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM