今天有个需求,要组装一个树状数据,前端小伙伴让我后端直接把数据套成数返给他,分享一下:
大概需求是这样的:
开始组装写代码:
/**
* 需要组装的树类
*/
@Data
public class Node {
private Integer Id;
private String name;
private Integer pId;
//子节点
private List<Node> treeNode=new ArrayList<>();
public Node(Integer id, Integer pId,String name) {
Id = id;
this.name = name;
this.pId = pId;
}
}
实现类
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class assembleTree {
public static void main(String[] args) {
Node first=new Node(1,0,"first");
Node second=new Node(2,1,"second");
Node third=new Node(3,2,"third");
Node fourth=new Node(4,1,"fourth");
Node fifth=new Node(5,4,"fifth");
List<Node> nodes = Arrays.asList(first, second, third, fourth, fifth);
List<Node> treeNode = buildTrees(nodes);
System.out.println(Arrays.deepToString(treeNode.toArray()));
}
private static List<Node> buildTrees(List<Node> nodes) {
//先过滤非第一层的数据 然后组装成一个map并且进行分组 分组就是根据pid到他对应的子节点数据
Map<Integer, List<Node>> nodesMap = nodes.stream().filter(node -> node.getPId() != 0)
.collect(Collectors.groupingBy(node -> node.getPId()));
//对nodes进行遍历循环 从map中拿到他对应节点的子节点 然后设置到treenode也就是子节点里面
nodes.forEach(node -> node.setTreeNode(nodesMap.get(node.getId())));
//过滤出pid=0的数据 也就是没有根节点的数据 直接返回 拼接完成
List<Node> tree = nodes.stream().filter(node -> node.getPId() == 0).collect(Collectors.toList());
return tree;
}
}
我这里是打印出二维数组给大家看下比较抽象,用流写非常简单 核心思想大致就是这样,给大家看下控制台输出: