forループでツリーを構築する
エンティティークラス
コアメソッドクラス
OK、上の階のコードを説明して、mainの方法の中で何もなくて、主にデータベースの中からloadデータ(データはidとpidを含まなければなりません)をシミュレートして、実体はきっと自分で建てたので、さもなくばchildrenというlistはありません.
コアトリックを見てみると、この方法ではmenuListのデータをすべて遍歴し、オタマジャクシがお母さんを探し始めました.対応するサブノードのエンティティを親ノードのchildren集合に追加するだけで、どのレベルのデータがあっても、自分の親ノードだけを探すことができます.menuListを印刷するとすべてのデータが表示されます.最後に親ノードのないノード、つまり木の最上階を引き抜くだけで、この木は既に構築されています~.
public class TreeNode {
private String id;
private String name;
private String parentId;
private List<TreeNode> children;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public List<TreeNode> getChildren() {
return children;
}
public void setChildren(List<TreeNode> children) {
this.children = children;
}
public TreeNode() {
super();
}
}
コアメソッドクラス
public class TreeMain {
public static void main(String[] args) {
List<TreeNode> menuList = new ArrayList<TreeNode>();
TreeNode t1 = new TreeNode();
t1.setId("1");
TreeNode t2 = new TreeNode();
t2.setId("2");
TreeNode t3 = new TreeNode();
t3.setId("3");
TreeNode t4 = new TreeNode();
t4.setId("4");
t4.setParentId("1");
TreeNode t5 = new TreeNode();
t5.setId("5");
t5.setParentId("4");
TreeNode tt5 = new TreeNode();
tt5.setId("7");
tt5.setParentId("4");
TreeNode t6 = new TreeNode();
t6.setId("6");
t6.setParentId("2");
menuList.add(t1);
menuList.add(t2);
menuList.add(t3);
menuList.add(t4);
menuList.add(t5);
menuList.add(t6);
menuList.add(tt5);
List<TreeNode> nodeList = TreeMain.list2Tree(menuList);
for (TreeNode t : nodeList) {
if (t.getChildren() != null) {
t.setChildren(null);
}
}
System.out.println("nodeList:" + JSON.toJSONString(nodeList));
}
}
//
public static List<TreeNode> list2Tree(List<TreeNode> menuList){
List<TreeNode> nodeList = new ArrayList<TreeNode>();
for(TreeNode node1 : menuList){
boolean addTheNode = true;
for(TreeNode node2 : menuList){
if(node1.parent_id != null && node1.parent_id.equals(node2.id)){
addTheNode = false;
if(node2.getChildren() == null){
node2.setChildren(new ArrayList<TreeNode>());
}
node2.getChildren.add(node1);
}
}
if(addTheNode){
nodeList.add(node1);
}
}
return nodeList;
}
}
OK、上の階のコードを説明して、mainの方法の中で何もなくて、主にデータベースの中からloadデータ(データはidとpidを含まなければなりません)をシミュレートして、実体はきっと自分で建てたので、さもなくばchildrenというlistはありません.
コアトリックを見てみると、この方法ではmenuListのデータをすべて遍歴し、オタマジャクシがお母さんを探し始めました.対応するサブノードのエンティティを親ノードのchildren集合に追加するだけで、どのレベルのデータがあっても、自分の親ノードだけを探すことができます.menuListを印刷するとすべてのデータが表示されます.最後に親ノードのないノード、つまり木の最上階を引き抜くだけで、この木は既に構築されています~.