美文网首页
列行数据处理成树形结构数据

列行数据处理成树形结构数据

作者: 伱个大西瓜 | 来源:发表于2018-11-27 10:00 被阅读0次

    语言 Java
    实现内容是一列数据中pid关联父级关系处理成树形结构数据

    • 数据结构
    [
        {
            "id": "1",
            "pid": "0",
            "name": "1"
        },
        {
            "id": "2",
            "pid": "1",
            "name": "2"
        },
        {
            "id": "3",
            "pid": "2",
            "name": "3"
        },
        {
            "id": "4",
            "pid": "0",
            "name": "4"
        }
    ]
    
    • 方法
    //Node就是对应上面数据结构中参数的实体类
    public List<Node> formatData(List<Node> nodeList,String pid){
        List<Node> list=new LinkedList<Node>();
        for (Node node:nodeList){
            if (node.getPid().equals(pid)){
                node.setChildren(formatData(nodeList,node.getId()));
                list.add(node);
            }
        }
        return list;
    }
    
    • 调用
      formatData(nodeList,"0") //因为第一级pid为0所以传入0
    • 效果
    [
        {
            "id": "1",
            "name": "1",
            "pid": "0",
            "children": [
                {
                    "id": "2",
                    "name": "2",
                    "pid": "1",
                    "children": [
                        {
                            "id": "3",
                            "name": "3",
                            "pid": "2",
                            "children": []
                        }
                    ]
                }
            ]
        },
        {
            "id": "4",
            "name": "4",
            "pid": "0",
            "children": []
        }
    ]
    

    相关文章

      网友评论

          本文标题:列行数据处理成树形结构数据

          本文链接:https://www.haomeiwen.com/subject/ldhdfqtx.html