I have map populated from database Data. I need to get values from there to Object. Field names in POJO and key names in Map object are different. I did it as the below. is there any effective way to do this
Map<String ,Object> map; //retrieved from database Employee e = new Employee(); if(map!=null) { if(map.containsKey("name")) { e.setFirstName(map.get("name")); } if(map.containsKey("ads")) { e.setMyAddress(map.get("ads")); } if(map.containsKey("country")) { e.setDealCountry(map.get("country")); } if(map.containsKey("keyId")) { e.Id(map.get("keyId")); } } public class Employee { String firstName; String id; String myAdreess; String dealCountry; //setter getters }
if(map.containsKey(…))checks. If yourEmployeehas no meaningful default values for the properties anyway, the worst thing that can happen withe.setFirstName(map.get("name"));without a check, is that it sets anullproperty tonullagain. Otherwise, if you have meaningful defaults, just use them, e.g.e.setFirstName(map.getOrDefault("name", "no name in db stored"));