How to obtain values from a multilevel HashMap stored in an ArrayList?
-
28-05-2021 - |
Domanda
Title says all.
Sample code:
ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> parentHash = new HashMap<String, Object>();
HashMap<String, String> childHash = new HashMap<String, String>();
childHash.put("child_id", "id")
childHash.put("name", "first last");
childHash.put("sex", "man");
parentHash.put("parent_id", "id");
parentHash.put("name", "first last");
parentHash.put("sex", "woman");
parentHash.put("children", childHash);
data.add(parentHash);
Everything looks okay if I print the ArrayList "data" on the screen (example):
[{parent_id=id, name=first last, sex=woman, children=[{
child_id=id, name=first last, sex=man
}]
}, {parent_id=id, name=first last, sex=woman, children=[{
child_id=id, name=first last, sex=man
}]
}];
So it's HashMap in HashMap and then in the ArrayList. I know how to retrieve value from the parent, but how do I retrieve value from the child?
Soluzione
Map<String, String> childData= (Map<String, String>) parent.get("children");
String childId= childData.get("child_id");
Also note that with your current structure, you can only add one child to a parent:
parentHash.put("children", childHash);
parentHash.put("children", anotherChildHash); //overrides childHash
Map<String, String> childData = (Map<String, String>) parent.get("children");
At the end of the code above, childData
contains anotherChildHash and childHash is not stored in the parentHash any longer.
Altri suggerimenti
The above answer will do want you want (though you'd need to check for childHash being null). However, have you considered defining your own classes? E.g.
public class Person {
private int person_id;
private String name;
private String sex;
// Handle zero to many children
private ArrayList<Person> children = new ArrayList<Person>();
// getters and setters follow.
}
Then later;
if ( parent.hasChildren() ) {
String name = parent.getChildren().get(0).getName();
}
Answer from assylias is correct. I want to add however that you could push your OO design a bit in order to encapsulate all this properly in classes. You will thus avoid to write hard-to-understand-hard-to-maintain code.