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

yaseco :

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!

daniu :

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());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112222&siteId=1