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?
I would iterate over both lists and build a map using the id as key and the object as value. Eg 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.