程序员在工作中经常碰到将实体类在后台组装成树状结构返回给前端。很麻烦又耗费时间。现在提供一个写好的工具类 直接拿去用就可以了。
样例:
import lombok.Data;import java.util.ArrayList;import java.util.List;import java.util.Objects;public class TreeDto { /** * 为了存储1对多的树形结构 */ private List childrenList; /** * 系统编号 */ private Long sysNo; /** * 父级 */ private Long parentSysNo; /** * 成本基本信息主键 */private Long costBaseSysNo; /** * 顺序 */ private Long score; /** * 项目名称 */ private String projectName; /** * 备注 */ private String remark; //把一个List转成树 public static List buildTree(List list, String pid){ List tree = new ArrayList(); for(TreeDto node : list){ if(Objects.equals(node.getParentSysNo(), pid)){ tree.add(findChild(node, list)); } } return tree; } public static TreeDto findChild(TreeDto node, List list){ for(TreeDto n : list){ if(Objects.equals(n.getParentSysNo(), node.getSysNo())){ TreeDto children = findChild(n, list); if(node.childrenList == null && children != null) { node.childrenList = new ArrayList(); } if(children != null) { node.getChildrenList().add(children); } } } return node; }
public Long getSysNo() { return sysNo; }
public void setSysNo(Long sysNo) { this.sysNo = sysNo; }
public Long getParentSysNo() { return parentSysNo; }
public void setParentSysNo(Long parentSysNo) { this.parentSysNo = parentSysNo; }
public Long getCostBaseSysNo() { return costBaseSysNo; }
public void setCostBaseSysNo(Long costBaseSysNo) { this.costBaseSysNo = costBaseSysNo; }
public Long getScore() { return score; }
public void setScore(Long score) { this.score = score; }
public String getProjectName() { return projectName; }
public void setProjectName(String projectName) { this.projectName = projectName; }
public String getRemark() { return remark; }
public void setRemark(String remark) { this.remark = remark; }
public List getChildrenList() { return childrenList; }
public void setChildrenList(List childrenList) { this.childrenList = childrenList; }}
在使用的过程中:
@PostMapping("/getServiceParamsTree") @AuditLog(operation = "查询数据服务参数tree", logType = EnumLogType.LOG) public JsonResult getTreeDto(@ApiParam @RequestBody ServiceParamSearchDto serviceParamSearchDto) {
if(serviceParamSearchDto == null) { throw new CustomException(MessageEnum.MSG_QUERY_PARAM_CANNOT_NULL.getMessage()); } List treeNodeDtoList = dmetExternalTableManageService.getServiceParamsTree(serviceParamSearchDto);
return JsonResult.SuccessAndHide(TreeNodeDto.buildTree(treeNodeDtoList, "0")); }
其中 JsonResult.SuccessAndHide(TreeNodeDto.buildTree(treeNodeDtoList, "0")); 0代表根目录的parentID是0 也可以根据实际情况自行调整。
领取专属 10元无门槛券
私享最新 技术干货