[英]Copying matching fields from one object list to another object list in java
Hi I have two list of objects.嗨,我有两个对象列表。 List1 and list2
列表 1 和列表 2
Employee list from App1来自 App1 的员工列表
list1
[id=1, name=Thomas, country=null],
[id=2, name=Smith, country=null],
[id=3, name=james, country=null],
[id=4, name=arun, country=null]]
GuestEmployee来宾员工
list2
[id=3, name=null, country=JAPAN, address=abc],
[id=2, name=null, country=USA, address=def],
[id=4, name=null, country=ENGLAND, address=hij]]
list1 has name details and list2 has country details. list1 具有名称详细信息,而 list2 具有国家/地区详细信息。 How can I copy country from list2 to list1 for corresponding object with Id as same as list1.
如何将 ID 与 list1 相同的相应 object 的国家/地区从 list2 复制到 list1。
In sql its quite easy we can join by ID column and do it.在 sql 中,我们可以很容易地通过 ID 列加入并执行此操作。 But here am hitting seperate API to read list2.
但这里我点击单独的 API 来读取 list2。
I can do create map from list2 and have EmpId as key and keep getting object from map and set details to list1.我可以从 list2 创建 map 并将 EmpId 作为键并继续从 map 获取 object 并将详细信息设置为 list1。
Was wondering is there any better approach to do this.想知道有没有更好的方法来做到这一点。
Basically I have to loop two times to get data into list1.基本上我必须循环两次才能将数据放入list1。
Loop1 to create Map and loop2 to copy fileds. Loop1 创建 Map 和 loop2 复制文件。
for(int i =0;i>list2.size();i++){
list1.get(i).setCountry(list2.get(i).getCountry);
}
Since the size is same, iterate over the second list and set the values of list1由于大小相同,迭代第二个列表并设置 list1 的值
HashMap<Integer, YourClass> map;
HashMap<Integer, YourClass> map;
for source data list.List<YourClass> list;
List<YourClass> list;
for dest data.get
method of map to quickly get the country of the Entity with that Id
get
方法快速获取具有该Id
的实体的国家/地区for (YourClass item : list) {
item.setCountry(map.get(item.getId()));
}
You should iterate both lists and check if the IDs are equal.您应该迭代两个列表并检查 ID 是否相等。
If you want to copy the list2 Country to list1 objects do the following如果要将 list2 Country 复制到 list1 对象,请执行以下操作
for (Employee e1: list1){
for (Employee e2: list2){
if (e1.getId()==e2.getId()) { //if its a String do .equals()
e1.setCountry(e2.getCountry();
}
}
}
for(Employee employee : list1){
for(Employee employee2 : list2) {
if(employee.getId() == employee2.getId()){
employee.setCountry(employee2.getCountry());
break;
}
}
}
short: You take every employee from list1, search for an employee with the same id from list2 and set the County if they match.简而言之:您从 list1 中获取每个员工,从 list2 中搜索具有相同 id 的员工,如果匹配,则设置县。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.