java生成树形结构(Java generate tree structure)

public class System extends BaseEntity  {   private static final long serialVersionUID = 1L;   /**    * 设备名称    */   @ApiModelProperty(value = "设备名称")   private String name;   /**    * code    */   @ApiModelProperty(value = "code")   private String code;   /**    * true false    */   @ApiModelProperty(value = "true false")   private Boolean collapsed;   /**    * 父主键id    */   @ApiModelProperty(value = "父主键id")   private Long parentId;   @TableField(exist = false)   private List<System> children;   private Integer sort; //排序   @TableField(exist = false) //是否有子集   private Boolean hasChildren;}

public R treeNode() { //1.查询1级菜单 List<System> systemList = systemService.list(new QueryWrapper<System>().eq(“parent_id”, 0)); List<System> list = systemService.list(); //查询全部 List<System> listNodes = new ArrayList<>(); for (System system : systemList) { System listNode = findListNode(list, system); listNodes.add(listNode); } return R.data(listNodes); }

/** * @param list 所有元素 * @param sys 父节点 * @return 树状jsonNode */ private System findListNode(List<System> list, System sys) { List<System> systemList = new ArrayList<>(); for (System system : list) { if (sys.getId().equals(system.getParentId())) { systemList.add(findListNode(list, system)); } } sys.setChildren(systemList); return sys; }

————————
public class System extends BaseEntity  {   private static final long serialVersionUID = 1L;   /**    * 设备名称    */   @ApiModelProperty(value = "设备名称")   private String name;   /**    * code    */   @ApiModelProperty(value = "code")   private String code;   /**    * true false    */   @ApiModelProperty(value = "true false")   private Boolean collapsed;   /**    * 父主键id    */   @ApiModelProperty(value = "父主键id")   private Long parentId;   @TableField(exist = false)   private List<System> children;   private Integer sort; //排序   @TableField(exist = false) //是否有子集   private Boolean hasChildren;}

public R treeNode() { //1.查询1级菜单 List<System> systemList = systemService.list(new QueryWrapper<System>().eq(“parent_id”, 0)); List<System> list = systemService.list(); //查询全部 List<System> listNodes = new ArrayList<>(); for (System system : systemList) { System listNode = findListNode(list, system); listNodes.add(listNode); } return R.data(listNodes); }

/** * @param list 所有元素 * @param sys 父节点 * @return 树状jsonNode */ private System findListNode(List<System> list, System sys) { List<System> systemList = new ArrayList<>(); for (System system : list) { if (sys.getId().equals(system.getParentId())) { systemList.add(findListNode(list, system)); } } sys.setChildren(systemList); return sys; }