The stream of additional fields returns 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 a List with containing all the values. If, for example, the optional "name" is missing, you should save an empty string. The result of the method should be a List with eq values: "1", "John", "," 5 ".

I created a thread:

Stream fields = Stream.of(id, name, lastname, number);

But I have no idea what's next.

Sincerely.

+4
source share
4 answers

You can use:

List<String> list = Stream.of(id, name, lastname, number)
        .map(op -> op.map(o -> o.toString()).orElse(""))
        .collect(Collectors.toList());

In each optional stream, you map it to it in Stringusing toString()from the class Object, and for nullyou will display it in empty String. Then you put it on a list.

+8

map , - :

fields.map(field -> field.orElse("").toString());

map , :

fields.map(field -> field.map(x -> x.toString()).orElse(""));
+2
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()); 
  • , , : , , ( trim() , )
  • , String.
0

:

List<String> result = fields.map(o -> o.orElse(""))  // provide default value
                            .map(o -> o.toString())  // cast to String
                            .collect(Collectors.toList()); // collect into List

.

0

Source: https://habr.com/ru/post/1689449/


All Articles