【JAVA】Java 实现无限层级的树形结构的数据

这篇博客介绍了如何使用Java和Mybatis-Plus来创建无限层级的树形结构数据。首先创建实体类和响应Vo类,然后通过查询所有公司数据并进行转换。接着,通过递归方法`getCompanyLevel`和`getChildren`来组装树状结构,将一级节点找出来并为其设置子节点。最后返回树结构列表。
摘要由CSDN通过智能技术生成

Java 实现无限层级的树形结构的数据(使用递归方法)

实现数据结构

{
    "code": 200,
    "msg": "成功!",
    "data": [
        {
            "id": "3de54a2de215454f84b30f74da895613",
			"pid": "-1"
            "companyUUId": "5380748e53ee48f8a1b67d34f64c93cf",
            "companyId": "ZGBW0001",
            "companyName": "xxxx有限公司",
            "childrenList": [
                {
                    "id": "202257d84d424db0a3cfd7791e5faf0e",
					"pid": "5380748e53ee48f8a1b67d34f64c93cf"
					"companyUUId": "2a723da6f60241af911ebe814f0f45f0",
					"companyId": "ZGBW000100",
					"companyName": "xxxx有限公司",
					"childrenList": [
						"id": "3258407ffa22434a8f353418f364dc5f",
						"pid": "2a723da6f60241af911ebe814f0f45f0"
						"companyUUId": "2b653a424a0c4ecdbfcab2d6bf78e160",
						"companyId": "ZGBW000199",
						"companyName": "xxxx有限公司",
						"childrenList": []
					]
                }
            ]
        }
    ]
}

1.创建实体类
在这里插入图片描述
2、创建返回Vo类
因为我这边使用的是mybatis-plus自带的增删改查方法,所以不能在实体类中新增其他属性
在这里插入图片描述
3、查询数据并组装成无线层级树状结构
使用递归方法实现树状结构

public List<AmpCompanyResponse> getCompanyLevel() {
   BaseApiService<Object> baseApiService = new BaseApiService<>();
   // 查询所有公司
   List<AmpCompanyTemporary> AmpList = ampCompanyTemporaryMapper.selectList(new QueryWrapper<AmpCompanyTemporary>().lambda()
           .orderByDesc(AmpCompanyTemporary::getCompanyLevel)
         .orderByAsc(AmpCompanyTemporary::getId));
  // 在此转把List<AmpCompanyTemporary>转换为list<AmpCompanyResponse>
  List<AmpCompanyResponse> bList = AmpList.stream().map(ampCompanyTemporary -> {
      AmpCompanyResponse ampCompanyResponse = new AmpCompanyResponse();
      BeanUtils.copyProperties(ampCompanyTemporary, ampCompanyResponse);
      return ampCompanyResponse;
  }).collect(Collectors.toList());

  // 存放树结构的数据
  List<AmpCompanyResponse> ampCompanyTreeList = new ArrayList<>();
  if (bList.size() > 0 && bList != null) {
      // 找到所有的一级节点存放在一个list中
      List<AmpCompanyResponse> parntList = new ArrayList<>();
      for (AmpCompanyResponse pList : bList) {
      	// 父节点的pID为 -1,这边按自己实际情况来判断
          if ("-1".equals(pList.getPId())) {
              parntList.add(pList);
          }
      }
      // 为一级节点设置子节点 ,getChildren采用递归算法
      for (AmpCompanyResponse amp : parntList) {
          AmpCompanyResponse companyResponse = new AmpCompanyResponse();
          companyResponse = amp;
          companyResponse.setChildrenList(getChildren(amp.getCompanyUUId(), bList));
          ampCompanyTreeList.add(amp);
      }
  }
  return ampCompanyTreeList;
}
/**
  * 递归组装树节点数据
  *
  * @param id   父节点id
  * @param list 所有数据
  * @return
*/
public List<AmpCompanyResponse> getChildren(String id, List<AmpCompanyResponse> list) {
  List<AmpCompanyResponse> childrenList = new ArrayList<>();
  // 子节点
  for (AmpCompanyResponse children : list) {
      if (id.equals(children.getPId())) {
          childrenList.add(children);
      }
  }
   // 把子节点的子节点循环一遍
  for (AmpCompanyResponse cList : childrenList) {
      cList.setChildrenList(getChildren(cList.getCompanyUUId(),list));
  }
  return childrenList;
}

效果:
在这里插入图片描述

无限Java递归) 2007-02-08 10:26 这几天,用java写了一个无限极的递归写的,可能代码不够简洁,性能不够好,不过也算是练习,这几天再不断改进。前面几个小图标的判断,搞死我了。 package com.nickol.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nickol.utility.DB; public class category extends HttpServlet { /** * The doGet method of the servlet. * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println(""); out.println(""); out.println(" Category" + "" + "body{font-size:12px;}" + "" + "" + ""); out.println(" "); out.println(showCategory(0,0,new ArrayList(),"0")); out.println(" "); out.println(""); out.flush(); out.close(); } public String showCategory(int i,int n,ArrayList frontIcon,String countCurrent){ int countChild = 0; n++; String webContent = new String(); ArrayList temp = new ArrayList(); try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(n==1){ if(rs.next()){ webContent += "";//插入结尾的减号 temp.add(new Integer(0)); } webContent += " ";//插入站点图标 webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,"0"); } if(n==2){ webContent += "\n"; }else{ webContent += "\n"; } while(rs.next()){ for(int k=0;k<frontIcon.size();k++){ int iconStatic = ((Integer)frontIcon.get(k)).intValue(); if(iconStatic == 0){ webContent += "";//插入空白 }else if(iconStatic == 1){ webContent += "";//插入竖线 } } if(rs.isLast()){ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(0)); }else{ webContent += "";//插入结尾的直角 } }else{ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入未结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(1)); }else{ webContent += "";//插入三叉线 } } if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += " ";//插入文件夹图标 }else{ webContent += " ";//插入文件图标 } webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,countCurrent+countChild); countChild++; } webContent += "\n"; DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return webContent; } public boolean checkChild(int i){ boolean child = false; try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(rs.next()){ child = true; } DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return child; } } --------------------------------------------------------------------- tree.js文件 function changeState(countCurrent,countChild){ var object = document.getElementById("level" + countCurrent + countChild); if(object.style.display=='none'){ object.style.display='block'; }else{ object.style.display='none'; } var cursor = document.getElementById("cursor" + countCurrent + countChild); if(cursor.src.indexOf("images/tree_minus.gif")>=0) {cursor.src="images/tree_plus.gif";} else if(cursor.src.indexOf("images/tree_minusbottom.gif")>=0) {cursor.src="images/tree_plusbottom.gif";} else if(cursor.src.indexOf("images/tree_plus.gif")>=0) {cursor.src="images/tree_minus.gif";} else {cursor.src="images/tree_minusbottom.gif";} var folder = document.getElementById("folder" + countCurrent + countChild); if(folder.src.indexOf("images/icon_folder_channel_normal.gif")>=0){ folder.src = "images/icon_folder_channel_open.gif"; }else{ folder.src = "images/icon_folder_channel_normal.gif"; }
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值