[英]Copying matching fields from one object list to another object list in java
嗨,我有两个对象列表。 列表 1 和列表 2
来自 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]]
来宾员工
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 具有名称详细信息,而 list2 具有国家/地区详细信息。 如何将 ID 与 list1 相同的相应 object 的国家/地区从 list2 复制到 list1。
在 sql 中,我们可以很容易地通过 ID 列加入并执行此操作。 但这里我点击单独的 API 来读取 list2。
我可以从 list2 创建 map 并将 EmpId 作为键并继续从 map 获取 object 并将详细信息设置为 list1。
想知道有没有更好的方法来做到这一点。
基本上我必须循环两次才能将数据放入list1。
Loop1 创建 Map 和 loop2 复制文件。
for(int i =0;i>list2.size();i++){
list1.get(i).setCountry(list2.get(i).getCountry);
}
由于大小相同,迭代第二个列表并设置 list1 的值
HashMap<Integer, YourClass> map;
用于源数据列表。 使用 Id 字段值作为 map 中的键。List<YourClass> list;
对于目标数据。get
方法快速获取具有该Id
的实体的国家/地区for (YourClass item : list) {
item.setCountry(map.get(item.getId()));
}
您应该迭代两个列表并检查 ID 是否相等。
如果要将 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;
}
}
}
简而言之:您从 list1 中获取每个员工,从 list2 中搜索具有相同 id 的员工,如果匹配,则设置县。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.