Daniel
Daniel

Reputation: 1676

How to collect a map key-value into a list

Given the following map declaration

Map<Integer, Integer> map;

I want to collect all the keys and all the values together into a single List<Integer> using a single stream that iterates over the map's entries just once.

So far, I have only managed to do that using two separate stream iterations; one for the keys and one for the values.

Can it be done in one pass?

Upvotes: 2

Views: 2902

Answers (3)

Bohemian
Bohemian

Reputation: 425398

Try this:

List<Integer> numbers = map.entrySet().stream()
    .flatMap(e -> Stream.of(e.getKey(), e.getValue()))
    .collect(Collectors.toList());

Upvotes: 4

njzk2
njzk2

Reputation: 39403

Assuming you have a function Integer t(K key, V value),

map.entrySet()
    .stream()
    .map(entry -> t(entry.key, entry.value))
    .collect(Collectors.toList());

Upvotes: 0

Edward Peters
Edward Peters

Reputation: 4062

Map.entrySet().stream().flatMap(...) should do it for you. Each Entry has getKey() and getValue(), so you should be able to compose those into 2-length streams in the flatMap lambda, then just wrap it all up with a list collector.

Alternatively, look at using .entrySet().reduce() to build up a list element by element.

Upvotes: 3

Related Questions