I have a stream and would like to check if all match a filter. If all match, return true
.
But, if the stream is empty, I\'d like to return false>
The following code will work (I tested it).
public static boolean validate(Stream stream) {
return stream.reduce((whatever1, whatever2) -> Whatever.someCheck(whatever1) ? whatever2 : whatever1)
.map(Whatever::someCheck).orElse(false);
}
How it works? We use reduce
operation to check that every element matches the predicate, if it fails, we keep returning the failing one (in ternary operation). At the end, we map the reduced Whatever
object to boolean, and if it's true: then all matched and this is not empty (orElse(false)
).