如何将List转换为Optional <list>?

时间:2016-06-15 15:50:22

标签: java java-8 optional

如何将List转换为Optional<List>

以下代码产生编译错误:

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;
}

2 个答案:

答案 0 :(得分:6)

Optional.of(mealList)会返回Optional<List<UserMeal>>,而不是List<Optional<UserMeal>>

要获得所需的List<Optional<UserMeal>>,您应该使用List包装Optional的每个元素:

List<Optional<UserMeal>> resultList = 
    mealList.stream()
            .map(Optional::ofNullable)
            .collect(Collectors.toList());

注意我使用了Optional::ofNullable而不是Optional::of,因为如果您的输入NullPointerException包含任何空元素,后者会生成List

答案 1 :(得分:2)

featlist到Optional的简单转换

Optional.ofNullable(mealList)