java_扁平<--->树转换的思路和方法参考

扁平转树形笔记

1.通过先找到根节点,然后在递归子节点的方法找子节点的子节点

public static List<Good> list2tree(List<Good> list){
        List<Good> resList = new ArrayList<>();
        for (Good good : list) {
            // 找到根节点
            if (good.getpId() == 0){
                Good root = getChild(good, list);
                resList.add(root);
            }
        }
        return resList;
    }
	// 找子节点方法
    public static Good getChild(Good parentNode,List<Good> list){
        for (Good good : list) {
            if (good.getpId() == parentNode.getId()){
                if (parentNode.getChildren() == null){
                    parentNode.setChildren(new ArrayList<>());
                }
                parentNode.getChildren().add(getChild(good, list));
            }
        }
        return parentNode;
    }

2.利用map集合的特性,将pid相同的元素归类到同一集合中用map存储pid为键元素集合为值

    public static List<Good> list2treeForMap(List<Good> list){
        // 通过相同的父节点,将数据分类
        Map<Integer,List<Good>> mapForPid = list.stream().collect(Collectors.groupingBy(good -> good.getpId()));
        // 遍历传入的集合
        List<Good> res = new ArrayList<Good>();
        for (Good good : list) {
            if (good.getpId() == 0){ // 根节点
                res.add(good);
            }
            // 获取通过id获取子节点数据
            List<Good> goodList = mapForPid.get(good.getId());
            if (goodList != null && goodList.size() > 0) { // 有子节点
                if (good.getChildren() == null){
                    good.setChildren(new ArrayList<>());
                }
                good.setChildren(goodList);
            }
        }
        return res;
    }

树形转扁平

public static List<Good> tree2list(List<Good> treeList){
        List<Good> resList = new ArrayList<>();
        for (Good good : treeList) {
            if (good.getChildren() != null && good.getChildren().size() > 0){
                resList.addAll(tree2list(good.getChildren()));
            }
            good.setChildren(null);
            resList.add(good);
        }
        return resList;
    }
}

你可能感兴趣的:(java,算法,数据结构,推荐算法)