eL_
eL_

Reputation: 177

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.

Upvotes: 4

Views: 1346

Answers (4)

user8537036
user8537036

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()); 
  1. Create a stream
  2. Add a filter which will keep the values if two condition are respected: they are not null and if it is true the string value is not empty (the trim() method permits to remove the empty chars which are on the left and the right of the value)
  3. Use a map method in order to transform objects which are Long instances into String instances
  4. Use a collect method in order to retrieve values

Upvotes: 0

Felipe
Felipe

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

Aaron
Aaron

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

See it in action.

Upvotes: 0

ByeBye
ByeBye

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

Related Questions