简体   繁体   中英

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

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.

Simple conversion of mealList to Optional

Optional.ofNullable(mealList)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM