Home > Net >  How to convert a list of java objects into a list of maps
How to convert a list of java objects into a list of maps

Time:05-02

I have the following domain object

Class Student {
    private int id;
    private String name;
    private int age;
}

and I have a List<Student>

How do I convert that into a list of map as follows

[{
    "id": 1,
    "name": "abc",
    "age": 2
}, {
    "id": 2,
    "name": "pqr",
    "age": 3
}]

CodePudding user response:

Easiest way would be to create a method toHashMap() in your Student class:

public LinkedHashMap<String,Object> toHashMap(){
    LinkedHashMap<String, Object> h = new LinkedHashMap<>();
    h.put("Id",id);
    h.put("Name", name);
    h.put("Age",age);
    return h;
}

I use a LinkedHashMap to preserve the insertion order. Once that is done, try this:

List<Student> ls = new ArrayList<>();
ls.add(new Student(12123,"Tom",12));
ls.add(new Student(12354,"George",21));
ls.add(new Student(12245,"Sara",16));
ls.add(new Student(17642,"Caitlyn",11));


List<LinkedHashMap<String,Object>> names = ls.stream().map(Student::toHashMap).collect( Collectors.toList() );

System.out.println(names);

Output: [{Id=12123, Name=Tom, Age=12}, {Id=12354, Name=George, Age=21}, {Id=12245, Name=Sara, Age=16}, {Id=17642, Name=Caitlyn, Age=11}]

CodePudding user response:

I'd say getting the object and iterating on the declared fields is good enough for what you're trying to do. Something like this:

private static List<Map<String,Object>> objectsToMap(List<Object> objects) throws IllegalAccessException {
  List<Map<String,Object>> result = new ArrayList<>();
  for (Object object : objects) {
    Map<String,Object> map = new HashMap<>();
    for (Field field : object.getClass().getDeclaredFields()) {
      var oldAccessibility = field.canAccess(object);
      field.setAccessible(true);
      var value = field.get(object);
      map.put(field.getName(), value);
      field.setAccessible(oldAccessibility);
    }
    result.add(map);
  }
  return result;
}

Nevertheless, it seems like you're trying to convert an ordinary object to JSON strings and there are libraries that to that super well. Check out this stackoverflow thread about conversion of objects to json if this is really what you're trying to achieve.

  • Related