Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 299
yaseco Avatar asked Dec 30 '25 04:12

yaseco


2 Answers

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());
like image 135
daniu Avatar answered Dec 31 '25 19:12

daniu


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.

like image 27
Rogue Avatar answered Dec 31 '25 17:12

Rogue