Copy HashMap of different type

How can I copy content of one HashMap<String,AddressDTO> to another HashMap<String,AddressBO> of a different type. There is no inheritance between AdressDTO and AddressBO ,both are POJOs with the same set of attributes:

AddressDTO addDTO = new AddressDTO();
addDTO.setAdd1("add1");
addDTO.setAdd2("add2");
addDTO.setAddtype("pri");
addDTO.setCity("city");


Map<String,Object> map1  = new HashMap<String,Object>();
map1.put("primary", addDTO);

Map<String,Object> map2  = new HashMap<String,Object>(map1);
AddressBO addnew = (AddressBO) map2.get("primary");
//this will give me runtime error AddressDTO cannot be cast to AddressBO    
System.out.println(addnew.getAdd1());
System.out.println(addnew.getAdd2());
System.out.println(addnew.getAddtype());

Answers


You can loop through the results of entry set which will give you the key value pairs and allow you to copy.

Also, HashMap takes a map. Probably other maps do too.


You cannot cast one Object to another based on field similarity only. You should use inheritance, or use some kind of transformer to create AddressBO from AddressDTO

If both Object contains exactly the same fields, there is no need for two classes.


There are various tools available that will use reflection to copy the values.

Alternatively you could just set the reference in the new map to be the same as the old map (then they will both share the same HashMap).

But it sounds like your real problem is mapping from the DTO to the BO.

For example if you create a constructor for the BO that accepts a DTO and creates a new BO from it then you could just do:

for (Entry<String, DTO> e: map1) {
    map2.put(e.getKey(), new BO(e.getValue()));
}

Need Your Help

Android developer Json & Pubnub

android json gson pubnub

Hi I wrote a code to publish a json with the Pubnub Channel:

Deleting files when user logouts or session end

.net asp.net vb.net file global-asax

I'm trying to delete files created by current user when he/she clicks logout button