Reputation: 321
I need to convert array of Map to a model class which contains memeber variable as array of POJO without looping through variables. For eg as follows:
Map<String,String>[] StudentArray= new HashMap[2];
Map<String,String> map1= new HashMap<String,String>();
map1.put("id","1");
map1.put("name","ABC");
Map<String,String> map2= new HashMap<String,String>();
map1.put("id","1");
map1.put("name","DEF");
StudentArray[0]=map1;
StudentArray[1]=map2;
Model class is:
class Student{
private String id;
private String name;
}
class StudentArray{
Student[] student;
}
I need to convert array of map to StudentArray model POJO.
Upvotes: 1
Views: 360
Reputation: 90
Streams in Java 8 helps in implementing internal iteration. Below piece of code will work.
List<Student> studentList = Arrays.stream(StudentArray).map(studentMap->
getStudentObject(studentMap)).collect(Collectors.toList());
Here studentMap will iterate as an instance from StudentArray[] and below method will convert each of these instance to Student POJO class, which is collected in List studentList.
Use com.fasterxml.jackson.core:jackson-databind:2.7.3 jar to use ObjectMapper's convertValue method:
private Student getStudentObject(Map studentMap){
ObjectMapper m = new ObjectMapper(); // // jackson's objectmapper
return m.convertValue(studentMap, Student.class);
}
Upvotes: 2