Given three functions like this:
private Optional<Integer> abc() {
return Optional.of(6);
}
private Optional<Integer> def() {
return Optional.of(3);
}
private Optional<Integer> ghi() {
return Optional.of(9);
}
If I want to check if one of the three functions return something which is greater than 5 (of course wrapped in Optional), in a traditional imperative style I would do it like this:
if( abc().get() > 5 || def().get() > 5 || ghi().get() > 5) {
......// Do something
} // I am not doing get() without checking ifPresent() just for simplicity sake
This would only go into function abc()
and skip def()
and ghi()
, because the first expression returns true. Which is a good optimization.
Now if I write the same in a functional style using Streams,
if( Stream.of(abc(), def(), ghi()).anyMatch(integer -> integer.get() > 5)) {
.........
}
I thought the same would happen, i.e. only abc()
will be called. But it calls all three functions. Isn't it redundant to check other two functions when there is anyMatch()
?
It is same in the case of noneMatch()
; the flow goes through whole Stream. I am just wondering: Isn't it really a bad thing to traverse the whole stream (especially if the stream has many values), even if the condition is met at the first element?