简体   繁体   中英

Copying matching fields from one object list to another object list in java

Hi I have two list of objects. List1 and list2

Employee list from 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. How can I copy country from list2 to list1 for corresponding object with Id as same as list1.

In sql its quite easy we can join by ID column and do it. But here am hitting seperate API to read list2.

I can do create map from list2 and have EmpId as key and keep getting object from map and set details to list1.

Was wondering is there any better approach to do this.

Basically I have to loop two times to get data into list1.

Loop1 to create Map and loop2 to copy fileds.

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

  1. Create class for your entity
  2. Create map HashMap<Integer, YourClass> map; for source data list. Use Id field value as a key in map.
  3. Create List<YourClass> list; for dest data.
  4. Iterate your dest list of item and use get method of map to quickly get the country of the Entity with that Id
for (YourClass item : list) {
   item.setCountry(map.get(item.getId()));
}

You should iterate both lists and check if the IDs are equal.

If you want to copy the list2 Country to list1 objects do the following

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM