IsaacLevon
IsaacLevon

Reputation: 2570

Java streams: Map<Enum, List<A>> to List<B>

I want to do the following using Java streams:

I have a Map<Enum, List<A>> and I'd like to transform it to List<B> where B has the properties Enum, A.

So for every key and every item in the list of that key I need to make an item B and to collect all of them to a List<B>.

How can it be done using Java streams?

Thanks!

Upvotes: 2

Views: 412

Answers (3)

Naman
Naman

Reputation: 31868

A simple forEach solution for that would be :

List<B> bList = new ArrayList<>();
map.forEach((key, value) -> value.forEach(val -> bList.add(new B(key, val))));

Upvotes: 1

daniu
daniu

Reputation: 14999

You can flatMap the entries of the map into Bs.

List<B> bList = map.entrySet().stream()
    // a B(key, value) for each of the items in the list in the entry
   .flatMap(e -> e.getValue().stream().map(a -> new B(e.getKey(), a)))
   .collect(toList());

Upvotes: 6

Rogue
Rogue

Reputation: 11483

I'm going to refer to B as Pair<Enum, A> for the sake of this example. You can use #flatMap and nested streams to accomplish it:

List<Pair<Enum, A>> myList =
    //Stream<Entry<Enum, List<A>>>
    myMap.entrySet().stream()
    //Stream<Pair<Enum, A>>
    .flatMap(ent -> 
        //returns a Stream<Pair<Enum, A>> for exactly one entry
        ent.getValue().stream().map(a -> new Pair<>(ent.getKey(), a)))
    .collect(Collectors.toList()); //collect into a list

Simply put you can utilize Map#entrySet to retrieve a collection of the map entries that you can stream. #flatMap will take a return value of streams for each element in the stream, and combine them.

Upvotes: 2

Related Questions