I have a use case in my Spring boot application as follows:
I would like to fetch the id
field value from the response with the following function:
String id = getIdFromResponse(response);
If I don't get any id in the response, then I check if the id
field is present in the request argument with the following function:
String id = getIdFromRequest(request);
As of now, I am invoking them sequentially. But I would like to make these two functions run parallelly, I would like to stop as soon as I get an id from either of them.
I am wondering if there is any way to implement this using streams
in Java 8.
You can use something like this:
String id = Stream.<Supplier<String>>of(
() -> getIdFromResponse(response),
() -> getIdFromRequest(request)
)
.parallel()
.map(Supplier::get)
.filter(Objects::nonNull)
.findFirst()
.orElseThrow():
The suppliers are needed, because when you don't use them, then both requests are still executed sequentially.
I also assumed that your methods return null
when nothing is found, so I had to filter these values out with .filter(Objects::nonNull)
.
Depending on your use case, you can replace .orElseThrow()
with something different, like .orElse(null)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With