Is it possible to write something like this and to avoid checking if elements are not null and collections not empty:
response.getBody()
.getRequestInformation()
.getRequestParameters().get(0)
.getProductInstances().get(0)
.getResultParameters()
If you want to chain Optional
, you can use its map(Function<? super T,? extends U> mapper)
method to call the mapper function only if it is not null
and use flatMap(Stream::findFirst)
to get the first element of your Collection
as next:
Optional<List<ResultParameterClass>> parameters = Optional.ofNullable(response)
.map(ResponseClass::getBody)
.map(BodyClass::getRequestInformation)
.map(RequestInformationClass::getRequestParameters)
.map(Collection::stream)
.flatMap(Stream::findFirst)
.map(RequestParameterClass::getProductInstances)
.map(Collection::stream)
.flatMap(Stream::findFirst)
.map(ProductInstanceClass::getResultParameters);
Is it possible to return the list if present in
Optional
, or if not present then return something like newArrayList<ResultParameterClass>()
?
Yes it is, you simply need to use orElseGet(Supplier<? extends T> other)
or orElse(T other)
to provide a default value, the result won't be an Optional
anymore but a List<ResultParameterClass>
.
So the code would then be:
List<ResultParameterClass> parameters = Optional.ofNullable(response)
...
.map(ProductInstanceClass::getResultParameters)
.orElseGet(ArrayList::new);