java 如何将列表转换为 Optional<List>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37840200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a List to Optional<List>?
提问by Pavel Klindziuk
How can I convert a List
to Optional<List>
?
如何将 a 转换List
为Optional<List>
?
The following code produces a compilation error :
以下代码产生编译错误:
public Collection<Optional<UserMeal>> getAll() {
Comparator comparator = new SortedByDate();
List<UserMeal> mealList = new ArrayList<>(repository.values());
Collections.sort(mealList,comparator);
Collections.reverse(mealList);
**List<Optional<UserMeal>> resultList = Optional.of(mealList);**
return resultList;
}
回答by Eran
Optional.of(mealList)
returns an Optional<List<UserMeal>>
, not a List<Optional<UserMeal>>
.
Optional.of(mealList)
返回一个Optional<List<UserMeal>>
,而不是一个List<Optional<UserMeal>>
。
To get the desired List<Optional<UserMeal>>
, you should wrap each element of the List
with an Optional
:
为了得到想要的List<Optional<UserMeal>>
,你应该换行的每个元素List
有Optional
:
List<Optional<UserMeal>> resultList =
mealList.stream()
.map(Optional::ofNullable)
.collect(Collectors.toList());
Note I used Optional::ofNullable
and not Optional::of
, since the latter would produce a NullPointerException
if your input List
contains any null elements.
注意我使用了Optional::ofNullable
and not Optional::of
,因为NullPointerException
如果您的输入List
包含任何空元素,后者会产生 a 。
回答by shijin raj
Simple conversion of mealList to Optional
mealList 到 Optional 的简单转换
Optional.ofNullable(mealList)
Optional.ofNullable(mealList)