Tometoyou Tometoyou - 1 month ago 21
Java Question

How to map two lists of objects by id efficiently

I have a

List
of objects (
List 1
) that I'm looping through. Each object has an
id
string associated with it. I have another list (
List 2
) containing a different type of object. I want to map the objects in
List 2
to my
List 1
objects.
List 1
has a
getId()
function and
List 2
has a
getList1Id()
function, that gives the
id
of the object its supposed to map to in
List 1
. How do I do this in the most efficient way possible?

Answer

I would iterate over both lists and build a map using the id as key and the object as value. E.g. for the first list:

Map<Integer, Object> map1 = new HashMap<>();
for (Object o : list1) {
    map1.put(o.getId(), o);
}

Do the same for the second list:

Map<Integer, Object> map2 = new HashMap<>();
for (Object o : list2) {
    map2.put(o.getId(), o);
}

Now you can relate an object in one list to an object in the other by calling get with a given id.