废话不多说系列,直接上代码。(一切看代码!)
一、完整代码示例
(1)创建 VO 实体类
import lombok.Data; // Lombok 注解
import java.util.List;
@Data
public class NodeVO {
private String id;
private String name;
private String pid; // 上级ID
private List<NodeVO> children; // 子节点集合
public NodeVO(String id, String name, String pid) {
this.id = id;
this.name = name;
this.pid = pid;
}
}
(2)list 转树形方法
public static List<NodeVO> streamToTree(List<NodeVO> treeList, String parentId) {
List<NodeVO> list = treeList.stream()
// 过滤父节点
.filter(parent -> parent.getPid().equals(parentId))
// 把父节点children递归赋值成为子节点
.map(child -> {
child.setChildren(streamToTree(treeList,child.getId()));
return child;
}).collect(Collectors.toList());
return list;
}
(3)测试示例
public static void main(String[] args) {
NodeVO NodeVO1 = new NodeVO("1", "山东省", "0");
NodeVO NodeVO2 = new NodeVO("2", "青岛市", "1");
NodeVO NodeVO3 = new NodeVO("3", "市北区", "2");
NodeVO NodeVO4 = new NodeVO("4", "济南市", "1");
NodeVO NodeVO5 = new NodeVO("5", "浙江省", "0");
NodeVO NodeVO6 = new NodeVO("6", "杭州市", "5");
NodeVO NodeVO7 = new NodeVO("7", "西湖区", "6");
List<NodeVO> list = Arrays.asList(NodeVO1, NodeVO2, NodeVO3, NodeVO4, NodeVO5, NodeVO6, NodeVO7);
// 默认指定父节点id为0
List<NodeVO> nodeVOList = streamToTree(list, "0");
System.out.println(JSON.toJSONString(nodeVOList));
}
结果展示:
[{
"children": [{
"children": [{
"children": [],
"id": "3",
"name": "市北区",
"pid": "2"
}],
"id": "2",
"name": "青岛市",
"pid": "1"
}, {
"children": [],
"id": "4",
"name": "济南市",
"pid": "1"
}],
"id": "1",
"name": "山东省",
"pid": "0"
}, {
"children": [{
"children": [{
"children": [],
"id": "7",
"name": "西湖区",
"pid": "6"
}],
"id": "6",
"name": "杭州市",
"pid": "5"
}],
"id": "5",
"name": "浙江省",
"pid": "0"
}]