I have a few Optional fields with String and Long values:
Optional<Long> id;
Optional<String> name;
Optional<String> lastname;
Optional<Long> number;
....
I would like to return List with contains all of the values. If e.g optional "name" is no present, should be stored empty String. Result of method should be List with values e.q: "1", "John", "", "5".
I made stream:
Stream fields = Stream.of(id, name, lastname, number);
But I have no idea what next.
Regards.
You can use:
List<String> list = Stream.of(id, name, lastname, number)
.map(op -> op.map(o -> o.toString()).orElse(""))
.collect(Collectors.toList());
On each optional in stream you will map it into it's String
version using toString()
from Object
class and for null
you will map it into empty String
. Than, you will collect it into list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With