Skip to content Skip to sidebar Skip to footer

How To Write A Recursive Method For Finding Parent And Child

This is to save the details with recursive. Here I want to get the details from the Database and set into my bean with a recursive method. So I can dispaly in angularUi tree format

Solution 1:

Instead of recursive I would suggest to go an extra step and store all elements in a HashMap

// a map containing all elements searchable by the rowId
HashMap<String, MultiAdminComponent> idToItem = new HashMap<>();
// a set containing all elements that don't have a parent (id: 1, 2, 3, etc.)
Set<MultiAdminComponent> rootItems = new HashSet<>();

for (MultiAdminComponent item : componentList) {
    // build the id->item map
    idToItem.put(item.getRowId(), item);
}

for (MultiAdminComponent item : componentList) {
    String parentId = getParentId(item.getRowId());
    if (parentId == null) {
        // this item has no parent -> it is a root item
        rootItems.add(item);
    } else {
        // This item has a parent -> look the parent up
        MultiAdminComponent parent = idToItem.get(parentId);
        parent.getItems().add(item);
    }
}

// rootItems now contains all MultiAdminComponents which do not have a parent, with the correct hierarchy for all items

getParentId could be something like this:

privateStringgetParentId(String id) {
    int lastDot = id.lastIndexOf(".");
    if (lastDot == -1) {
        returnnull;
    }
    return id.substring(0, lastDot);
}

If you can guarantee that componentList will go through the list from parents to children, you can combine both for-loops.

Post a Comment for "How To Write A Recursive Method For Finding Parent And Child"