
cn.meteor.common.util.TreeUtil Maven / Gradle / Ivy
package cn.meteor.common.util;
import cn.hutool.core.util.ObjectUtil;
import cn.meteor.common.model.TreeModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 组装树工具类
*
* @author ths
*/
public class TreeUtil {
/**
* 构建树
*
* @param nodes 节点列表
* @param 泛型
* @return 树结构
*/
public static > List buildTree(List nodes) {
List result = new ArrayList<>();
Map noteMap = nodes.stream().collect(Collectors.toMap(T::getId, o -> o));
noteMap.values().stream().filter(node -> {
T parent = noteMap.get(node.getParentId());
if(ObjectUtil.isNull(parent)){
return true;
}
if(ObjectUtil.isNull(parent.getChildren())){
parent.setChildren(new ArrayList<>());
}
if (ObjectUtil.notEqual(parent.getId(), node.getId())) {
parent.getChildren().add(node);
return false;
}
return true;
}).forEach(result::add);
return result;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy