[英]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>
. 我已将
Map
中的值提取到List
但得到了List<Optional<TXN_PMTxnHistory_rb>>
,我想将其转换为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>
. 我想获得一个
List<TXN_PMTxnHistory_rb>
。
Filter out all the empty values and use map
to obtain the non-empty values: 过滤掉所有空值并使用
map
获取非空值:
List<TXN_PMTxnHistory_rb> listHistory_rb6 =
listHistory_rb5.values()
.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
It's possible to do this using a method called flatMap
on the stream of Optional
s which will remove any 'empty' Optional
s. 可以在
Optional
s流上使用一个名为flatMap
的方法来执行此操作,该方法将删除任何“空” 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". Flatmap实际上执行两件事 - “映射”和“展平”。 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. 在映射阶段,它调用您传入的任何方法并期望返回一个新流 - 在这种情况下,原始
List
每个Optional
都将成为包含1或0值的Stream
。
The flatten phase will then create a new Stream
containing the results of all the mapped Stream
s. 然后, 展平阶段将创建一个包含所有映射的
Stream
的结果的新Stream
。 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. 因此,如果
List
有2个可Optional
,一个为空,一个为full,则生成的Stream
将包含来自第一个映射Stream
0个元素和来自第二个的1个值。
Another option is to get all values and then filter out nulls
: 另一种选择是获取所有值,然后过滤掉
nulls
:
List<TXN_PMTxnHistory_rb> listHistory_rb6 =
listHistory_rb5.values().stream()
.map(opt -> opt.orElse(null))
.filter(Objects::nonNull)
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.