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.

Answer

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.

Leave a Reply

Your email address will not be published. Required fields are marked *