一、前言
我们在日常开发中,必不可少的就是树形结构。有的时候可以使用mybatis的resultMap进行转化,有的时候需要进行Java进行手动转化为树结构。今天和大家分析一个JDK8新特性Stream来实现list到树形结构的转化!
二、创建返回前端的实体类VO
代码语言:javascript复制@Data
@AllArgsConstructor
@ToString
@NoArgsConstructor
public class NodeVO {
private Integer id;
private String name;
private Integer pid;
private List<NodeVO> children;
public NodeVO(Integer id, String name, Integer pid) {
this.id = id;
this.name = name;
this.pid = pid;
}
}
三、list转树形方法
代码语言:javascript复制 public static List<NodeVO> streamToTree(List<NodeVO> treeList, Integer parentId) {
return treeList.stream()
// 过滤父节点
.filter(parent -> Objects.equals(parent.getPid(), parentId))
// 把父节点children递归赋值成为子节点
.peek(child -> child.setChildren(streamToTree(treeList,child.getId()))).collect(Collectors.toList());
}
四、测试
代码语言:javascript复制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,"福田区",4);
NodeVO NodeVO6 = new NodeVO(6,"广西省",0);
NodeVO NodeVO7 = new NodeVO(7,"梧州市",6);
NodeVO NodeVO8 = new NodeVO(8,"长洲区",7);
List<NodeVO> list = new ArrayList<>();
list.add(NodeVO1);
list.add(NodeVO2);
list.add(NodeVO3);
list.add(NodeVO4);
list.add(NodeVO5);
list.add(NodeVO6);
list.add(NodeVO7);
list.add(NodeVO8);
// 默认父节点id为0
List<NodeVO> nodeVOList = streamToTree(list,0);
System.out.println(JSON.toJSONString(nodeVOList));
}
结果展示:
代码语言:javascript复制[{
"children": [{
"children": [{
"children": [],
"id": 3,
"name": "天河区",
"pid": 2
}],
"id": 2,
"name": "广州市",
"pid": 1
}, {
"children": [{
"children": [],
"id": 5,
"name": "福田区",
"pid": 4
}],
"id": 4,
"name": "深圳市",
"pid": 1
}],
"id": 1,
"name": "广东省",
"pid": 0
}, {
"children": [{
"children": [{
"children": [],
"id": 8,
"name": "长洲区",
"pid": 7
}],
"id": 7,
"name": "梧州市",
"pid": 6
}],
"id": 6,
"name": "广西省",
"pid": 0
}]
参考文献:《Java使用stream把list集合转化为树形结构(一行解决超简单递归)》