John Baum John Baum - 1 year ago 102
Java Question

Converting one hashmap to another by a flattening operation

If I have a mapping from

Map<User, List<Foo>>
map1 where Foo looks like below:


And id is unique across all Foos, I am looking for a way to convert the Map> to a map of
Map<Integer, Foo>
where the key is a foo id. I have tried the below but can only get to a mapping of
Map<Integer, List<Foo>>

Map<Integer, List<Foo>> idToListOfFoo = originalMap.values().stream()

How can I achieve this efficiently?

Answer Source

There is a collector for this. It is called toMap. You use it like this:

Map<Integer, Foo> idToListOfFoo = originalMap.values().stream()
        .collect(Collectors.toMap(Foo::getId,  Function.identity()));

toMap takes 2 functions as parameteres: The first is used to get the key from the element and the second to get the value for the map.

Function.identity() returns a function that just returns its input. Hence the key is the id and the value is the object itself in the resulting map.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download