简体   繁体   中英

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.

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:

    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. Thanks.

Just use Stream#anyMatch(...) with a Predicate that returns the value itself.

// 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 . It will continue to consume the Stream if all it sees is false values.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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