Reputation: 177
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.
Upvotes: 4
Views: 1346
Reputation:
List<String> ls = Stream.of(a, b).filter(o -> o != null && !o.trim().equals("")).map(o -> o instanceof Long ? String.valueOf(o) : o).collect(Collectors.toList());
Upvotes: 0
Reputation: 143
You can use the map method of the stream to manipulate the content of your stream, something like the below code:
fields.map(field -> field.orElse("").toString());
The optional also has a map method that can be used when manipulating the stream:
fields.map(field -> field.map(x -> x.toString()).orElse(""));
Upvotes: 2
Reputation: 24812
This works :
List<String> result = fields.map(o -> o.orElse("")) // provide default value
.map(o -> o.toString()) // cast to String
.collect(Collectors.toList()); // collect into List
Upvotes: 0
Reputation: 6956
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.
Upvotes: 8