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!
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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With