[英]How to map two lists of objects by id efficiently
I have a List
of objects ( List 1
) that I'm looping through. 我有一个
List
对象(的List 1
我通过循环)。 Each object has an id
string associated with it. 每个对象都有一个与之关联的
id
字符串。 I have another list ( List 2
) containing a different type of object. 我还有另一个包含不同类型对象的列表(
List 2
)。 I want to map the objects in List 2
to my List 1
objects. 我想将
List 2
的对象映射到我的List 1
对象。 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
. List 1
具有getId()
函数, List 2
具有getList1Id()
函数,该函数给出应该映射到List 1
中的对象的id
。 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. 我将遍历两个列表,并使用id作为键,将对象作为值来构建地图。 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. 现在,可以通过调用具有给定id的get来将一个列表中的对象与另一个列表中的对象相关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.