I have an entity called Item
. Item
can have parents and children.
Each Item
has the following methods:
getParent()
--> returns an Item
getChildren()
--> returns a List<Item>
isLeaf()
--> returns a Boolean
getName()
--> returns a String
Each level in the hierarchy is a level in a construction site, for example level 1 is House 1, level 2 is Floor 1, level 3 is Room and level 4 is Window.
I have a List<Item
and I need to sort them like this:
I think I need some kind of recursive function but I can't imagine how it has to be.
I've already researched for sorting objects with a hierarchy in Java but I don't find anything similar to my case.
I would appreciate any help and sorry if the question is not clear 100% but it is quite hard to describe.
Thanks.
It would indeed be recursive. The trouble is that a simple recursive compare would only work if the two nodes were on the same level.
// Same level compare
int compareSameLevel(Item item) {
int c = 0;
if (this.getParent != null) {
c = compare(this.getParent(), item.getParent());
}
return (c != 0) ? c : getName().compare(item.getName());
}
But you could adjust the levels to find a common level and assume that the children go after the parent:
// Compare on any level
int compare(Item item) {
Item thisItem = this;
int thisLevel = thisItem.level();
int itemLevel = item.level();
for (int i = thisLevel; i > itemLevel; i--) {
thisItem = thisItem.getParent();
}
for (int j = itemLevel; j > thisLevel; j--) {
item = item.getParent();
}
int c = compareSameLevel(thisItem, item);
return c != 0 ? c : (thisLevel > itemLevel ? -1 : 1);
}
This is just to give you an idea. It is not tested or compiled.
Pseudo code: Try like this
private static void printChildElements(List<Object> childNodes) {
for(Object childNode : childNodes) {
List<Object > childElements = childNode .....;
if(childElements.size() > 0) {
printChildElements( childElements);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.