在Java 8中,可以使用Stream API和Lambda表达式来实现List转换为Tree的转换。下面是一个可能的优雅写法:

List<BusinessDomainPo> businessDomains = new ArrayList<>();
// 假设已经将数据填充到businessDomains中

List<BusinessDomainPo> treeBusinessDomains = businessDomains.stream()
        .filter(businessDomain -> businessDomain.getParentId() == null)
        .map(rootBusinessDomain -> convertToTree(rootBusinessDomain, businessDomains))
        .collect(Collectors.toList());

private static BusinessDomainPo convertToTree(BusinessDomainPo root, List<BusinessDomainPo> allBusinessDomains) {
    List<BusinessDomainPo> children = allBusinessDomains.stream()
            .filter(businessDomain -> Objects.equals(businessDomain.getParentId(), root.getId()))
            .map(childBusinessDomain -> convertToTree(childBusinessDomain, allBusinessDomains))
            .collect(Collectors.toList());
    root.setChildren(children);
    return root;
}

这个写法使用了Stream API的filter()和map()方法来过滤和映射数据,然后使用递归的方式构建树形结构。最终使用collect()方法将结果收集到一个新的List中。

Java 8优雅实现List<BusinessDomainPo>转Tree<BusinessDomainPo>

原文地址: https://www.cveoy.top/t/topic/qDl3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录