集合转换Tree

import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Data
public class SalePointVehicleModelVO implements Serializable {

    private static final long serialVersionUID = 1L;

    public List<SalePointVehicleModelVO> children;

    public SalePointVehicleModelVO() {
        children = new ArrayList<>();
    }


    public static SalePointVehicleModelVO copySalePointVehicleModel(SurSalePointVehicleModel model) {
        SalePointVehicleModelVO vo = new SalePointVehicleModelVO();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    public static List<SalePointVehicleModelVO> buildTree(List<SurSalePointVehicleModel> models) {
        if (CollectionUtils.isEmpty(models)) {
            return null;
        }
        List<SalePointVehicleModelVO> roots = models.stream().map(model -> SalePointVehicleModelVO.copySalePointVehicleModel(model)).filter
                (model -> model.getParentId() == null || model.getParentId() == 0).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(roots)) {
            return null;
        }
       roots.stream().forEach(root -> {
           buildChildTree(models,root);
        });
        return roots;
    }

    private static void buildChildTree(List<SurSalePointVehicleModel> models, SalePointVehicleModelVO vehicleModel) {
        models.stream().forEach(model -> {
            if (vehicleModel.getId().equals(model.getParentId())) {
                vehicleModel.getChildren().add(SalePointVehicleModelVO.copySalePointVehicleModel(model));
            }
        });
        List<SalePointVehicleModelVO> child = vehicleModel.getChildren();
        if (!CollectionUtils.isEmpty(child)) {
           child.stream().forEach(childModel -> {
               buildChildTree(models,childModel);
           });
        }
    }
}

posted @ 2025-08-25 17:03  亲爱的阿道君  阅读(3)  评论(0)    收藏  举报