I have an expensive method that I only want to call it when necessary in a stream. Here is an example:
public static Optional<MyObject> findTarget(String input, List<MyObject> myList) {
return Stream.concat(myList.stream(), expensive().stream()).filter(o -> o.hasName(input)).findFirst();
}
The goal is to find the target MyObject
from myList
based on the input
value, but if its not in myList
ONLY then it will call expensive()
to return a bigger list and look from there.
The above example does not do that, as it seems Stream.concat
will call expensive()
already before consuming all of myList
.
An ugly solution I can think of is to do it in two steps, e.g.:
return myList.stream().filter(o -> o.hasName(input)).findFirst().or(
() -> expensive().stream().filter(o -> o.hasName(input)).findFirst());
But then I will have to repeat the filter and the rest twice.
Is there any better solution or even a single liner of Stream that does that?