Java树形结构中根据父类节点查找全部子类节点

java

  上一篇文章介绍了两种树形结构数据整合json格式的方法,第一种方法中有根据父类获取全部子类的方法,这里单独拿出来再说一下。

  仍然是利用递归来整合,代码如下:

    //根据父节点获取全部子节点

public static List<TreeBuilder.Node> getChildren(Integer pid,List<TreeBuilder.Node> nodeList){

List<TreeBuilder.Node> resultList = new ArrayList<>();

if (null != nodeList && nodeList.size() > 0){

try{

for (TreeBuilder.Node layer : nodeList) {

if(pid == layer.getParentId()){

//添加子级节点

resultList.add(layer);

//递归获取深层节点

resultList.addAll(getChildren(layer.getId(),nodeList));

}

}

}catch (Exception e){

System.out.println(e);

}

}

return resultList;

}

  看测试代码:

package com.johanChan.WebSocket.controller;

import com.alibaba.fastjson.JSON;

import com.johanChan.WebSocket.utils.BuildTree;

import com.johanChan.WebSocket.utils.CommonUtils;

import com.johanChan.WebSocket.utils.Tree;

import com.johanChan.WebSocket.utils.TreeBuilder;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller

public class TreeController {

List<TreeBuilder.Node> nodeList ;

List<Tree<TreeBuilder.Node>> treeList;

{

nodeList = CommonUtils.buildNode();

treeList = CommonUtils.buildTree();

}

@ResponseBody

@RequestMapping("/getTreeJson")

public String getTreeJson() {

// List<TreeBuilder.Node> nodeList = CommonUtils.buildNode();

// String result = CommonUtils.buildTree(nodeList);

List<Tree<TreeBuilder.Node>> resultList = BuildTree.build(treeList);

String result = JSON.toJSONString(resultList);

return result;

}

@ResponseBody

@RequestMapping("/getChildren/{id}")

public String getChildren(@PathVariable("id") Integer id) {

// List<TreeBuilder.Node> nodeList = CommonUtils.buildNode();

List<TreeBuilder.Node> result = CommonUtils.getChildren(id,nodeList);

// String jsonStr = JSON.toJSONString(result);

String jsonStr = CommonUtils.buildTree(result);

return jsonStr;

}

}

  方法:getChildren/{id}就是了,启动项目看看效果:

   数据整理一下:

[

{

"children":[

{

"code":"豫A-1",

"id":15,

"level":5,

"name":"金水区",

"parentId":11

}

],

"code":"豫A",

"id":11,

"level":4,

"name":"郑州",

"parentId":7

},

{

"code":"豫B",

"id":12,

"level":4,

"name":"开封",

"parentId":7

},

{

"code":"豫C",

"id":13,

"level":4,

"name":"洛阳",

"parentId":7

},

{

"code":"豫R",

"id":14,

"level":4,

"name":"南阳",

"parentId":7

}

]

  已经得到了想要的数据,大家可以根据自己的需要修改一下就OK了。

以上是 Java树形结构中根据父类节点查找全部子类节点 的全部内容, 来源链接: utcz.com/z/394752.html

回到顶部