John Baum
John Baum

Reputation: 3331

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:

Foo
User
id
name
age

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()
            .flatMap(List::stream)
            .collect(Collectors.groupingBy(Foo::getId));

How can I achieve this efficiently?

Upvotes: 1

Views: 104

Answers (1)

Leon
Leon

Reputation: 3036

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

Map<Integer, Foo> idToListOfFoo = originalMap.values().stream()
        .flatMap(List::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.

Upvotes: 4

Related Questions