I want to terminate execution of stream when found first value. However, when I run code below it shows up that two methods are called even if value is present from first method.
public static void main(String[] args) {
Optional<String> s = Stream.of(first(), second())
.filter(Optional::isPresent)
.findFirst()
.flatMap(Function.identity());
System.out.println(s.get());
}
private static Optional<String> first() {
System.out.println("first");
return Optional.of("someValue");
}
private static Optional<String> second() {
System.out.println("second");
return Optional.empty();
}
I checked in docs that:
- isPresent
Return {@code true} if there is a value present, otherwise {@code false}.
- findFirst()
Returns an {@link Optional} describing the first element of this stream, or an empty {@code Optional} if the stream is empty. If the stream has no encounter order, then any element may be returned.
So the first condition it met, and the second seems to be also fulfilled cause it returns:
first
second
someValue
How to quit execution if first value present, and not execute second method?