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.

asked Nov 18, 2020 at 11:25
\$\endgroup\$
1
  • \$\begingroup\$ Why not use an if statement here? \$\endgroup\$ 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());
answered Dec 18, 2020 at 14:24
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.