Home > Blockchain >  Convert map to list in java
Convert map to list in java

Time:12-28

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);

CodePudding user response:

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.

  • Related