Convert map to list in java

tom

I have a map like this. Map<Long,Map<String, Double>>.I want to convert this map to Student list. My Student class is :

public class Student {
private long student_id;
private String name;
private Double salary;

//getter and setters
}

I used object mapper but it is not working because map contains another map in my structure.

 final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
 final List<Student> studentList = mapper.convertValue(map, Student.class);
Arun Gowda

Using jackson to do this is probably an overkill if not it's not even a solution.

Assuming you are using java 8 or above and every student_id has at least one entry, the following should work.

return input.entrySet().stream().map(entry-> {
    Student s = new Student();
    s.setStudent_id(entry.getKey());
    Map.Entry<String,Double> nameAndSalary = entry.getValue().entrySet().iterator().next();
    s.setName(nameAndSalary.getKey());
    s.setSalary(nameAndSalary.getValue());
    return s;
}).collect(Collectors.toList());

If every student_id doesn't need to have an entry for name and salary, you should handle it accordingly with null/empty checks.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related