简体   繁体   中英

Java sort List of objects with a hierarchy alphabetically

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:

  • Item 1 (House 1 > Floor 1 > Room 1 > Bath)
  • Item 2 (House 1 > Floor 1 > Room 2 > Basement)
  • Item 3 (House 1 > Floor 1 > Room 2 > Door)
  • Item 4 (House 1 > Floor 1 > Room 2 > Window)
  • Item 5 (House 1 > Floor 2 > Room 1 > Door)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM