I have this piece of code:
final ResultDO response = transformJsonToResponseDO(rawDataResponse, ResultDO.class);
return Optional.ofNullable(response)
.map(results -> createPOIs(Collections.singletonList(response), providerResponse))
.orElse(Collections.emptyList());
The important part is that: response is an object of type ResultDO. Within an Optional I want to call that method createPois(). Methot createPois wants a list of ResultDO, but there I will always have it only element because of that I wrapped in a Collections.singletonList().
As I wrote it, is it the right way, with that .map() ?
I don't want to use if(response != null) ...
Maybe it is worth to mention that createPois() return a list of some other types. A list of Points.
-
\$\begingroup\$ Why not use an if statement here? \$\endgroup\$Andrew– Andrew2020年11月21日 16:26:22 +00:00Commented Nov 21, 2020 at 16:26
1 Answer 1
This looks mostly correct. IMO, should not use response
in the map function, but results
. I.e.
final ResultDO response = transformJsonToResponseDO(rawDataResponse, ResultDO.class);
return Optional.ofNullable(response)
.map(results -> createPOIs(Collections.singletonList(results), providerResponse))
.orElse(Collections.emptyList());
Even though they are the same in this case, typically this is how you are supposed to use Optional when you're not wrapping in #ofNullable.
Furthermore, this lets you put it all on one line:
return Optional.ofNullable(transformJsonToResponseDO(rawDataResponse, ResultDO.class))
.map(results -> createPOIs(Collections.singletonList(results), providerResponse))
.orElse(Collections.emptyList());