Skip to content
Advertisement

iterate the List and set the value with data available in another list [closed]

I have the below two List objects, i want to iterate the addrMappingList and set the Person to the field by getting the person object from personList. Below is the sample code.

List<Person> personList = getPersonList();
List<AddressMapping> addrMappingList = personToAddressMappingList();

Sample AddressMapping class:

class AddressMapping {

 private int id;
 private Person person;
 ..
}

Sample Person class:

Class Person{
  private int personId;
  private String personName;
  ...
 }

I want to iterate the addrList and for each addrList element i want to set the personList element. Tried the below code:

for(AddressMapping addrMapping : addrMappingList){
  for(Person p : personList){
     addrMapping.setPerson(p);
  }
}

I should not iterate the Person inside the addrMapping as shown in the above code, any inputs would be helpful. PS: Two list doesn’t have any data to compare and set the value.

Advertisement

Answer

You only need one iteration to do that. Since you actually need the index, it also means you can use a good old for loop for this:

List<Person> personList = getPersonList();
List<AddressMapping> addrMappingList = personToAddressMappingList();

for(int i = 0; i < personList.size(); i++) {
    addrMappingList.get(i).setPerson(personList.get(i));
}

Of course, since personList and addrMappingList have the same number of elements, this is an option.

UPDATE

If by “with Java8” you mean using a more “modern” syntax, you could also use the following.

List<Person> personList = getPersonList();
List<AddressMapping> addrMappingList = personToAddressMappingList();

IntStream.range(0, personList.size())
             .forEach(i -> addrMappingList.get(i).setPerson(personList.get(i)));

With all that, I think the first approach is better because this is a very simple function not worth overcomplicating. I don’t really know if there is any performance benefits (And if there are, at what point they are noticeable), but unless it’s significant I prefer readability (The KISS principle).

Advertisement