1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Why not use an if statement here? \$\endgroup\$
    – Andrew
    Commented Nov 21, 2020 at 16:26

1 Answer 1

1
\$\begingroup\$

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());
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.