Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream of optional fields return values

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.

like image 334
eL_ Avatar asked Dec 24 '22 12:12

eL_


1 Answers

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.

like image 164
ByeBye Avatar answered Jan 08 '23 03:01

ByeBye