Reputation: 105
I have extracted values from a Map
into a List
but got a List<Optional<TXN_PMTxnHistory_rb>>
, and I want to convert it into List<TXN_PMTxnHistory_rb>
.
My code:
List<Optional<TXN_PMTxnHistory_rb>> listHistory_rb6 =
listHistory_rb5.values()
.stream()
.collect(Collectors.toList());
I'd like to obtain a List<TXN_PMTxnHistory_rb>
.
Upvotes: 3
Views: 246
Reputation: 18245
Another option is to get all values and then filter out nulls
:
List<TXN_PMTxnHistory_rb> listHistory_rb6 =
listHistory_rb5.values().stream()
.map(opt -> opt.orElse(null))
.filter(Objects::nonNull)
.collect(Collectors.toList());
Upvotes: 1
Reputation: 649
It's possible to do this using a method called flatMap
on the stream of Optional
s which will remove any 'empty' Optional
s.
List<TXN_PMTxnHistory_rb> listHistory_rb6 =
listHistory_rb5.values()
.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());
Flatmap is essentially performing two things - "mapping" and "flattening". In the mapping phase it calls whatever method you've passed in and expects back a new stream - in this case each Optional
in your original List
will become a Stream
containing either 1 or 0 values.
The flatten phase will then create a new Stream
containing the results of all the mapped Stream
s. Thus, if you had 2 Optional
items in your List
, one empty and one full, the resulting Stream
would contain 0 elements from the first mapped Stream
, and 1 value from the second.
Upvotes: 2
Reputation: 393791
Filter out all the empty values and use map
to obtain the non-empty values:
List<TXN_PMTxnHistory_rb> listHistory_rb6 =
listHistory_rb5.values()
.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
Upvotes: 7