Converting a List of pojo Class to a Jdom Tree?
I have a POJO class call LEVEL
& his class diagramm like this:
0,1
------------|
| |
| |
\|/ |
level-<>-------
In other words this:
public class Level
{
private int id;
private int label;
private Set<Level> labels;
private Level parent;
...
}
I have a method who retrieve from the database ALL the level in a List<Level>
.
I want for the jdom representation(using org.jdom
api) a开发者_运维百科 Tree (like a tree for your directories) like this
LEVEl 1
+++LEVEL 2
++++++LEVEL 3
LEVEL 4
LEVEL 5
I know the algorithm have to be recursive.
Do u have any solution ? Any tool to convert to java class to a jdom tree?
I don't know any library that would do exactly what you ask for.
Your class Level is correct, but not the only option. You could also add a property Set<Level> children
. You could keep the parent
link or not (bi-directional relationship, or Many-To-One).
That might make your tree structure more natural...
For example, if you were using an ORM like Hibernate, your could just find the first level instance (in the list you receive from Hibernate), and you would already have your tree, simply ignore other instances.
Otherwise, an algorithmic solution could be:
- have all your instances in an
unprocessed
list - find all instances of the unprocessed, that have no parent ; add them to your tree, delete them from unprocessed.
- loop on the following :
- find all instances of the unprocessed, that have their parent in the tree (if the tree doesn't have an efficient implementation of
contains
, you can use a temporary Set for this). - add them to your tree, delete them from unprocessed.
- find all instances of the unprocessed, that have their parent in the tree (if the tree doesn't have an efficient implementation of
精彩评论