All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.yrm.tools.common.util.TreeUtil Maven / Gradle / Ivy

package cn.yrm.tools.common.util;

import cn.hutool.core.util.ReflectUtil;
import cn.yrm.tools.common.code.CommonConstant;
import cn.yrm.tools.common.vo.TreeItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
public class TreeUtil {

    public static  List convertListToTree(List list, Class clazz) {
        List treeList = new ArrayList<>();
        List resultTree = new ArrayList<>();
        // 转换对象 以及添加一级
        list.stream().forEach(item -> {
            T obj = null;
            try {
                obj = clazz.newInstance();
                BeanUtils.copyProperties(item, obj);
                treeList.add(obj);
                if (CommonConstant.ROOT_PARENT_ID.equals(ReflectUtil.getFieldValue(item, CommonConstant.PARENT_KEY_DEFINE))) {
                    resultTree.add(obj);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        });
        // 组合父子关系
        treeList.stream().forEach(item -> {
            Optional parentOptional = treeList.stream().filter(parent ->
                    parent.getId().equals(item.getPid())).findFirst();
            if (parentOptional != null && parentOptional.isPresent()) {
                T parent = parentOptional.get();
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(item);
            }
        });
        return resultTree;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy