递归实现不限层级嵌套结构

不限层级嵌套结构
一、将获取数据组装成一个嵌套结构的Map

private static List<Group> groupList = new ArrayList<>();
//groupList中存放多个多个组信息,group中有个上级id,根据上级id组装成嵌套格式

//存放所有的一级节点
public List<Object>getFinalGroupList() {
    List<Object> finalMap = new ArrayList<>();
    int index = 1;
    for (Group group : groupList) {
        Map<String,Object> groupMap = new LinkedHashMap<>();
        if (group.getGroupParentid().trim().equals("0")){
            groupMap.put("groupId",group.getGroupId());
            groupMap.put("groupName",group.getGroupName());
            groupMap.put("groupIndex",index);//第几层
            groupMap.put("child",getGroupChild(group.getGroupId()+"", index));
            finalMap.add(groupMap);
        }
    }
    return finalMap;
}

//递归获取所有子节点
private List<Object> getGroupChild(String groupId, int index) {
    List<Object> childGroups = new ArrayList<>();
    ++index;
    for (Group group : groupList) {
        Map<String,Object> groupMap = new LinkedHashMap<>();
        if (group.getGroupParentid().equals(groupId)){
            groupMap.put("groupId",group.getGroupId());
            groupMap.put("groupName",group.getGroupName());
            groupMap.put("groupIndex",index);
            groupMap.put("child",getGroupChild(group.getGroupId()+"",index));
            childGroups.add(groupMap);
        }
    }
    return childGroups;
}

效果如图所示:

[
    {
        "groupId": 1,
        "groupName": "组 1",
        "groupIndex": 1,
        "child": [
            {
                "groupId": 2,
                "groupName": "组 1.1",
                "groupIndex": 1,
                "child": [
                    {
                        "groupId": 3,
                        "groupName": "组 1.1.1",
                        "groupIndex": 2,
                        "child": [
                            
                        ]
                    },
                    {
                        "groupId": 7,
                        "groupName": "组 1.1.2",
                        "groupIndex": 3,
                        "child": [
                            
                        ]
                    }
                ]
            }
        ]
    },
    {
        "groupId": 5,
        "groupName": "组 2",
        "groupIndex": 1,
        "child": [
            
        ]
    }
]

二 、递归遍历Map获取里面所有的叶子节点

//将嵌套结构的json转换为json数组
JsonArray jsonArray = jsonParser.parse(paramStr).getAsJsonArray();
public void getGroupLeafs(JsonArray jsonArray){
    for (int i = 0; i < jsonArray.size(); i++) {
        JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
        JsonArray childArray =  jsonObject .get("child").getAsJsonArray();
        if (childArray.size() == 0){
            A a = new A();
            list.add(a);
        }else{
            getGroupLeafs(childArray);
        }
    }
}
展开阅读全文

没有更多推荐了,返回首页