问题描述:
给一组树形结构生成以下编号
1-1
1-1.1
1-1.2
1-2
1-2.1
1-2.1
废话不多说,直接看代码例子
model 结构:
public class TreeVO {
private String sqNum;
private Long id;
private Long parentId;
private List<TreeVO> childList;
}
例子全部代码 :
需要导入:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.66</version>
</dependency>
import com.alibaba.fastjson.JSON;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
public class TreeSequenceNumber {
public static void main(String[] args) {
TreeSequenceNumber treeSequenceNumber = new TreeSequenceNumber();
treeSequenceNumber.createSeqNum();
}
/**
* 给树结构创建编号
*/
void createSeqNum() {
//组装数据
List<TreeVO> treeList = createData();
//根节点生成序号
for (int i = 0; i < treeList.size(); i++) {
TreeVO treeVO = treeList.get(i);
String parentSeqNum = i + 1 + "";
treeVO.setSqNum(parentSeqNum);
//给每个根底下的子结构也生成编号
recursiveLoopCreateSeqNum(treeVO.getChildList(), parentSeqNum);
}
//打印最后结果
System.out.println(JSON.toJSONString(treeList));
}
/**
* 递归给根节点底下节点生成编号
* @param treeList
* @param parentSeqNum
*/
void recursiveLoopCreateSeqNum(List<TreeVO> treeList, String parentSeqNum) {
if (null == treeList || treeList.size() < 1) {
return;
}
for (int i = 0; i < treeList.size(); i++) {
TreeVO treeVO = treeList.get(i);
String childSeqNum = parentSeqNum + "-" + (i + 1);
treeVO.setSqNum(childSeqNum);
//递归
recursiveLoopCreateSeqNum(treeVO.getChildList(), childSeqNum);
}
}
/**
* 创建数据
*/
List<TreeVO> createData() {
//树形结构数据列表
List<TreeVO> treeVOList = new ArrayList<>();
//巴拉巴拉一堆造数据
TreeVO treeVO1 = new TreeVO();
treeVO1.setParentId(5L);
treeVO1.setId(1L);
TreeVO treeVO2 = new TreeVO();
treeVO2.setParentId(5L);
treeVO2.setId(2L);
TreeVO treeVO3 = new TreeVO();
treeVO3.setParentId(6L);
treeVO3.setId(3L);
TreeVO treeVO4 = new TreeVO();
treeVO3.setParentId(6L);
treeVO4.setId(4L);
List<TreeVO> treeVO5ChildList = new ArrayList<>();
treeVO5ChildList.add(treeVO1);
treeVO5ChildList.add(treeVO2);
TreeVO treeVO5 = new TreeVO();
treeVO5.setId(5L);
treeVO5.setParentId(0L);
treeVO5.setChildList(treeVO5ChildList);
List<TreeVO> treeVO6ChildList = new ArrayList<>();
treeVO6ChildList.add(treeVO3);
treeVO6ChildList.add(treeVO4);
TreeVO treeVO6 = new TreeVO();
treeVO6.setId(6L);
treeVO6.setParentId(0L);
treeVO6.setChildList(treeVO6ChildList);
treeVOList.add(treeVO5);
treeVOList.add(treeVO6);
return treeVOList;
}
/**
* 树形结构 model 类
*/
@Data
public static class TreeVO {
//序列号
private String sqNum;
//记录id
private Long id;
//父节点id
private Long parentId;
//子数据
private List<TreeVO> childList;
}
}
用该例子最终得到结果:
[{
"childList": [{
"id": 1,
"parentId": 5,
"sqNum": "1-1"
}, {
"id": 2,
"parentId": 5,
"sqNum": "1-2"
}],
"id": 5,
"parentId": 0,
"sqNum": "1"
}, {
"childList": [{
"id": 3,
"parentId": 6,
"sqNum": "2-1"
}, {
"id": 4,
"sqNum": "2-2"
}],
"id": 6,
"parentId": 0,
"sqNum": "2"
}]
本次分享语句:
肉体是拿来用的,而不是拿来伺候的