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

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

This card has several keys and optional values.

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

The specified method has a compilation error. How to get an additional list?

+4
source share
2 answers

you skip and return a value, do not forget that it Optional<List<Long>>is an optional object, which can have 1 list if it is present ....

you need instead List<Optional<Long>>

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

You don't even need to streamhere, just to put them together in List:

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

Source: https://habr.com/ru/post/1694951/


All Articles