Ganga
Ganga

Reputation: 607

How to get the optional values from a map as an optional list?

Map<Long, Optional<Long>> aMap = new HashMap<>();

This map has some keys and optional values.

Optional<List<Long>> valuesList = input.aMap().values().stream()
                            .collect(Collectors.toList());

The above way has compilation error. How do i get the optional list correctly?

Upvotes: 4

Views: 813

Answers (2)

Eugene
Eugene

Reputation: 120848

You don't even need to stream here, just to collect them to a List:

 List<Optional<Long>> list = new ArrayList<>(input.aMap().values());

Upvotes: 2

you missundertand the return value, dont forget that a Optional<List<Long>> is an optional object that can have 1 list if present....

you need instead a List<Optional<Long>>

List<Optional<Long>> valuesList = input.aMap()
                   .values()
                   .stream()
                   .collect(Collectors.toList());

Upvotes: 3

Related Questions