zoukankan      html  css  js  c++  java
  • java递归构建菜单树

     1 package testSimple;
     2 
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 
     6 public class BuildTree {
     7     public static void main(String[] args) {
     8         List<Tree> list = new ArrayList<Tree>();
     9         list.add(new Tree(1, "一级菜单", 0));
    10         list.add(new Tree(2, "二级菜单1", 1));
    11         list.add(new Tree(3, "二级菜单2", 1));
    12         list.add(new Tree(4, "二级菜单3", 1));
    13         list.add(new Tree(5, "三级菜单11", 2));
    14         list.add(new Tree(6, "三级菜单12", 2));
    15         list.add(new Tree(7, "三级菜单21", 3));
    16         list.add(new Tree(8, "三级菜单22", 3));
    17         list.add(new Tree(9, "三级菜单31", 4));
    18         list.add(new Tree(10, "三级菜单32", 4));
    19 
    20         List<Tree> result = buildTree(list, 0);
    21         System.out.println(result);
    22     }
    23 
    24     public static List<Tree> buildTree(List<Tree> list, int fid) {
    25         List<Tree> resultList = new ArrayList<Tree>();
    26         if (list == null || list.size() == 0 || fid < 0) {
    27             return null;
    28         }
    29         for (Tree tree : list) {
    30             if (tree.getFid() == fid) {
    31                 resultList.add(tree);
    32                 tree.setChildren(buildTree(list, tree.getId()));
    33             }
    34         }
    35         return resultList;
    36     }
    37 
    38 }
    39 
    40 class Tree {
    41     private int id;
    42     private String name;
    43     private int fid;
    44     private List<Tree> children;
    45 
    46     public Tree(int id, String name, int fid) {
    47         super();
    48         this.id = id;
    49         this.name = name;
    50         this.fid = fid;
    51     }
    52 
    53     public int getId() {
    54         return id;
    55     }
    56 
    57     public void setId(int id) {
    58         this.id = id;
    59     }
    60 
    61     public String getName() {
    62         return name;
    63     }
    64 
    65     public void setName(String name) {
    66         this.name = name;
    67     }
    68 
    69     public int getFid() {
    70         return fid;
    71     }
    72 
    73     public void setFid(int fid) {
    74         this.fid = fid;
    75     }
    76 
    77     public List<Tree> getChildren() {
    78         return children;
    79     }
    80 
    81     public void setChildren(List<Tree> children) {
    82         this.children = children;
    83     }
    84 
    85 }
  • 相关阅读:
    备考C++有感
    使用GridView来获取xml文件数据
    SQL 事务及实例演示
    MySQL数据分析-(12)表操作补充:字段属性
    以字符串为例,谈谈Python到底要学到什么程度
    MySQL数据分析-(9)库操作补充:用户管理和权限管理
    Python流程控制和缩进
    MySQL数据分析-(11)表补充:数据类型
    MySQL数据分析-(8)SQL基础操作之库操作
    外键
  • 原文地址:https://www.cnblogs.com/cxxjohnson/p/7308312.html
Copyright © 2011-2022 走看看