Home > Enterprise >  Best way to create one map by combining attributes from 2 maps
Best way to create one map by combining attributes from 2 maps

Time:06-10

Let's say I have the following 2 classes Relationship and Person with following attributes:

class Relationship {
   long childId;
   long parentId;
}
class Person {
   long id;
   String name;
}

And let's say I have the following 2 maps

Map<Long, Relationship> map1; // key=childIds, value=Relationship object with childId
Map<Long, Person> map2;       // key=parentIds, value=Person object

If I want a map combining the above 2 maps, where the key is childId and the value is Person, what is the best way to do that? I know I can simply iterate over using a loop, but is there an out of the box method for that?

Pseudocode for the iteration would look like:

map3 = new Map<Long, Person>;
for each entry e in map1{
   Person parent = map2.get(map1.get(e.value().parentId));
   map3.put(e.key(), parent);
}

CodePudding user response:

You can use a stream instead of looping:

Map<Long, Person> parentByChild = map1.values()
        .stream()
        .collect(Collectors.toMap(r -> r.childId, r -> map2.get(r.parentId)));
  • Related