we have the following requirement of creating recursive object tree from the list of objects.[Explorer tree style]
Let me explain by an example. Consider the foll. BusinessObject (BO) :
We get the List of BOs from a call to an external system which does not provide these BOs in tree form [i.e. parent-child tree relationship].It simply provides these BO with the code,desc and categoryPath attribute set. Now we have to get the parent-child relationship out of the List and populate the List<MyBO> children attribute appropriately.
Now we have to convert this List of BOs in another List<MyBO> such that the parent-child [Tree] relationship is maintained i.e. "com" should be top level and should contain ChildList of java,javaranch and hellowworld and so on each element should contain its subfolders as child.This will then be provided to the front end to be shown as an Explorer style TREE structure.
Hope i have clarified my requirements elaborately enough. I think using recursive logic can be a solution but i am not sure about how to get the parent-child relationship correct because the objects can be in any order.
So would appreciate if you can share your comments,views,ideas,code on this.
One thing you might consider doing is first sorting the list based on how many packages it contains, so com would come before com.x or com.y, and com.x would come before com.x.z. (you could probably sort on the number of . character). This will guarantee that your parents come before the children.
Then, without recursion, you could go down the list. If the current item starts with a package you have seen before, then you know it is a child, otherwise, it is a new package. For example, if the first item is com, you know that's a new package. Then, if you see com.x or com.x.y, since it starts with com, you know it's a child of com. It gets a little trickier, if the list goes right from com to com.x.y because you have to determine that com.x.y starts with com, rather than looking for an existing package com.x (but you could probably start with com.x and then if that doesn't exist, look for com).
I know this is a lot of text here, but hopefully I've explained clearly, but I'd be happy to answer any questions you might have. [ August 09, 2008: Message edited by: Jeff Storey ]
Put the paths in an arraylist. Find the root first. then In a loop go thru the list picking up the next leading part of the path and save it in a Set, removing any paths that are leaves (ie not continued). Create childern to the current node for all the path parts picked up so far. For example, a.b and a.c.e would find a as root, then fine b and c as the next part of the path under a. then find e as part path under a.c Some methods would be: