Search code examples
javadictionarydata-structuresjava-streamdeque

Get a list of map keys from a deque in Java


I have a deque

Deque<Map<int, String> cars = new LinkedList();

I want to use Java stream to collect all the keys from the deque map into a

List<int>. 

Is there any way to do this?

I tried something like

cars.stream().map(car -> car.keySet()).collect(Collectors.toList()

This question is different from the previous question. I want to collect all the keys, as opposed to removing a map from the deque.


Solution

  • Use flatMap():

    cars.stream()
        .map(Map::keySet)
        .flatMap(Set::stream)
        .collect(Collectors.toList())