Pavel Klindziuk
Pavel Klindziuk

Reputation: 45

How to convert a List to List<Optional>?

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

Upvotes: 2

Views: 25180

Answers (2)

shijin raj
shijin raj

Reputation: 91

Simple conversion of mealList to Optional

Optional.ofNullable(mealList)

Upvotes: 4

Eran
Eran

Reputation: 393791

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.

Upvotes: 9

Related Questions