I need to create a parent to child relationship of my records and would like to use hashmaps to store the data and then a TreeSet/Iterator to get the ordered value
The records are as follows and come in random order:
Record 1: Parent 1; Child 2
Record 2: Parent 2; Child 1
Record 3: Parent 1; Child 1
Record 4: Parent 3; Child 1
One way to do this would be to create a hashmap of {Parent} --> {SortedSet of children}. You can also have a separate SortedSet of parents or even store them in the hashmap. Here's how you'd add a child:
SortedSet parents = (SortedSet) map.get("root");
Parent p1 = (Parent) parents.first();
SortedSet children = (SortedSet) map.get(p1);
if (children == null) {
children = new TreeSet();
map.put(p1,children);
}
children.add(new Child("Child 1"));
To get your output, just iterate through the parents; for each parent, iterate through the SortedSet of children.
Alternatively, and especially if you need more than one level of parent to child relationships, consider creating a Node class which has as a field a SortedSet of children.
0
mred_mredAuthor Commented:
this definitely answered my question and i did seem to figure it out while waiting. thanks for the quick response.
i do have more than one level. where do i find the node class? or do i create this my self? class.child_node or something? or is this a java class that i can use.
No, you'd have to create the Node class yourself. A Node could be a parent or a child, depending on if it has any children. Of course, this is assuming that parents and children have basically the same information. In the Node class you'll probably want a "name" field, a "children" field (which would be a SortedSet of other Nodes), and any other information pertinent to a node.
0
Question has a verified solution.
Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.
SortedSet parents = (SortedSet) map.get("root");
Parent p1 = (Parent) parents.first();
SortedSet children = (SortedSet) map.get(p1);
if (children == null) {
children = new TreeSet();
map.put(p1,children);
}
children.add(new Child("Child 1"));
To get your output, just iterate through the parents; for each parent, iterate through the SortedSet of children.
Alternatively, and especially if you need more than one level of parent to child relationships, consider creating a Node class which has as a field a SortedSet of children.