Java List 递归生成树形结构

@Data
public class BaseTree> {
    
    private static final long serialVersionUID = 1L;

    @TableId(value = "id",type = IdType.AUTO)
    private Long id;

    private Long parentId;

    @TableField(exist = false)
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private List children = new ArrayList<>();
    
    public BaseTree() {}

    /**
      * 注意:children一定要new ArrayList<>();不然add会报错的
      * 核心思想就是先拿出list中所有的parentId,再拿出所有id,做差集 拿到的就是一级类目
      * 递归一级类目下的二级类目,再递归二级类目下的三级类目。。。然后把查到的相应子类目加入到父节点中
      */
    public static > List listToTree(List list) {
        Set parentIds = list.stream().map(BaseTree::getParentId).collect(Collectors.toSet());
        Set ids = list.stream().map(BaseTree::getId).collect(Collectors.toSet());
        parentIds.removeAll(ids);
        //递归查找子结点
        return list.stream()
                   .filter(tree -> parentIds.contains(tree.getParentId()))
                   .map(tree -> findChildren(tree, list))
                   .collect(Collectors.toList());
    }

    private static > T findChildren(T tree, List list) {
        list.stream()
            .filter(node -> node.getParentId().equals(tree.getId()))
            .map(node -> findChildren(node, list))
            .forEachOrdered(children -> tree.getChildren().add(children));
        return tree;
    }

   
    
}

也可以直接写在所在类的方法中

    public List listToTree(List list) {
        Set parentIds = list.stream().map(BasMallCatalogDTO::getParentId).collect(Collectors.toSet());
        Set ids = list.stream().map(BasMallCatalogDTO::getId).collect(Collectors.toSet());
        parentIds.removeAll(ids);
        //递归查找子结点
        return list.stream()
                .filter(tree -> parentIds.contains(tree.getParentId()))
                .map(tree -> findChildren(tree, list))
                .collect(Collectors.toList());
    }

    private BasMallCatalogDTO findChildren(BasMallCatalogDTO tree, List list) {
        list.stream()
                .filter(node -> node.getParentId().equals(tree.getId()))
                .map(node -> findChildren(node, list))
                .forEachOrdered(children -> tree.getChildren().add(children));
        return tree;
    }

你可能感兴趣的:(JAVA,java,开发语言)