从平面列表创建 Java 层次树集 [英] Creating a java hierarchial treeset from a flat list
问题描述
我有对象 T 的列表,它有一个父属性,其中顶部对象的父属性为空.我想将所有对象放入一个 TreeSet(或 TreeMap)中.顶级对象将是所有没有父对象(父对象为空)的根对象,它们将在它们之下有自己的子对象.
I have list of Objects T, it has a property of parent where the top objects parent property is null. I want to put all the objects into a TreeSet (or TreeMap). Top level objects will be all the root objects that has no parent (parent is null) and they will have their children under them.
像这样
o
/ | \
Ra Rb Rc -- Level Root Objects
/ | \ | \
Ca1 Ca2 Cb1 Cc1 Cc2 -- Level of First Children
/ \
Ca11 Ca12.............. -- Level of Second Children
所以我可以得到 Ra 并找到它的孩子 (Ca1, Ca2, Ca11, Ca12....)
So I can get Ra and find its children (Ca1, Ca2, Ca11, Ca12....)
更新:抱歉,可能不清楚,节点指向父节点,如果父节点为空,则它们是根节点.问题是父母需要了解它的孩子.但关系是相反的.
Update: Sorry may be it wasn't clear, nodes point to parents and if parent is null, they are root nodes. The problem is parents need to know its children. But the relationship is in the opposite direction.
class Node
{
private Node parent;
private String name;
}
推荐答案
这是我想出的解决方案
SortedSet<Node> nodeSet = new TreeSet<Node>(new Comparator<Node>() {
public int compare(Node node1, Node node2) {
if (node1.getParent() == null) {
if (node2.getParent() == null) {
return node1.getId().compareTo(node2.getId());
}
return -1;
}
if (node2.getParent() == null) return 1;
int parentCompare = node1.getParent().getId()
.compareTo(node2.getParent().getId());
if (parentCompare == 0)
return node1.getId().compareTo(node2.getId());
return parentCompare;
}
});
nodeSet.addAll(allData); // allData is the Node list
Map<Node, List<Node>> map = new HashMap<Node, List<Node>>();
for(Node node : nodeSet)
{
if(map.get(node)==null)
{
map.put(node, new ArrayList<Node>());
}
map.get(node).add(node);
Node parentNode = node.getParent();
while(parentNode!=null)
{
map.get(parentNode).add(node);
parentNode = parentNode.getParent();
}
}
// At this point I can get an element from map and see all children in values.
这篇关于从平面列表创建 Java 层次树集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!