Skip to content
Advertisement

Convert one Optional<List> to another Optional<List> in Java

How can I convert Optional List object from one type to another, for an example

JavaScript

ProductMultipleOptionViewModel

Type 1

JavaScript

Type 2

JavaScript

I want to convert from Optional<List<ProductMultipleOption>>to other Optional<List<ProductMultipleOptionViewModel>>. I tried the below code

JavaScript

With the above code, I am not able to access the option value inside map method

If product.getProductMultipleOption() is null return null or empty list.

Advertisement

Answer

You should rarely use Optional and Collections (like List or Set) together. Instead you should work with empty Collections. Also keep in mind that Optionals should not really be used for conditional logic, but rather as return values.

Either using a normal if statement:

JavaScript

Another variant:

JavaScript

Or if you really want to use Streams and Optionals (matter of taste):

JavaScript

Now that’s a lot of code for simply converting a nullable List. So why not return an empty List in the first place? Change product.getProductMultipleOption() to something like this:

JavaScript

That way you never have to worry about null checks. Because you’re simply working with an empty collection wherever you’re calling getProductMultipleOption().

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement