Adding two different group of objects to a list of groups I have two lists of Strings and two lists of objects. I need to copy the list of strings to the correspondence list of objects with specific values.

public List&lt;Name&gt; retrieveCitiesAndCountries(){
  List&lt;String&gt; list1 = new ArrayList&lt;String&gt;(); //list of cities
  List&lt;String&gt; list2 = new ArrayList&lt;String&gt;(); //list of countries
  list1 = retrieveListOfCities();
  list2 = retrieveListOfCountries();

  List&lt;Name&gt; namesList = new ArrayList&lt;Names&gt;();
  return namesList;
}


Name class

class Name{
  String name;
  String attrib;
  ..
}


I need to add both lists to namesList and add the respective attribs. For example, all cities should have City as their attribs and all countries should have Country as their attribs.

 for(int i=0;i&lt;list1.size();i++){
     Name name = new Name();        
     name.setName(list1.get(i));
     name.setAttrib("City");
     namesList.add(name);
   }

  for(int i=0;i&lt;list2.size();i++){
     Name name = new Name();        
     name.setName(list2.get(i));
     name.setAttrib("Country");
     namesList.add(name);
   }


I am wondering if there is any better way to do it.

I use namesList to return in JSON format.

@RequestMapping(value = "/names")
public @ResponseBody List&lt;Name&gt; retrieveCitiesAndCountries(){
    List&lt;Name&gt; namesList = retrievalServ.retrieveCitiesAndCountries();
    return namesList;
}
The Name() class has what I would call a half-assed constructor: it creates an object in a not-quite-initialized state, making it temporarily useless until the setters are called.  If you had a Name(String name, String attrib) constructor, then the code would be a lot less cumbersome.

You can also avoid using indexed loops.

for (String city : list1) {
    namesList.add(new Name(city, "City"));
}
for (String country : list2) {
    namesList.add(new Name(country, "Country"));
}