1. 程式人生 > >遞迴實現不限層級巢狀結構

遞迴實現不限層級巢狀結構

不限層級巢狀結構
一、將獲取資料組裝成一個巢狀結構的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);
        }
    }
}