How to convert a List to List<Optional>?

20,347

Solution 1

Optional.of(mealList) returns an Optional<List<UserMeal>>, not a List<Optional<UserMeal>>.

To get the desired List<Optional<UserMeal>>, you should wrap each element of the List with an 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.

Solution 2

Simple conversion of mealList to Optional

Optional.ofNullable(mealList)

Share:
20,347
Pavel Klindziuk
Author by

Pavel Klindziuk

Updated on January 23, 2021

Comments

  • Pavel Klindziuk
    Pavel Klindziuk about 3 years

    How can I convert a List to List<Optional>?

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