Nilesh Chauhan
Nilesh Chauhan

Reputation: 105

How to convert List<Optional<Type>> into List<Type>

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

Answers (3)

Oleg Cherednik
Oleg Cherednik

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

Nicko
Nicko

Reputation: 649

It's possible to do this using a method called flatMap on the stream of Optionals which will remove any 'empty' Optionals.

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 Streams. 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

Eran
Eran

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

Related Questions