package com.mzl.flower.utils; import com.mzl.flower.base.Node; import lombok.experimental.UtilityClass; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; @UtilityClass public class TreeBuilderUtil { /** * list to tree * 默认以parentId 为空的为根节点 * * @param dirs * @return */ public List buildListToTree(List dirs) { List roots = findRoots(dirs, null); List notRoots = (List) CollectionUtils.subtract(dirs, roots); for (Node root : roots) { root.setChildren(findChildren(root, notRoots)); } return roots; } /** * list to tree * 以parentId 为 rootParentIdValue值 的为根节点 * * @param dirs * @param rootParentIdValue * @return */ public List buildListToTree(List dirs, Object rootParentIdValue) { List roots = findRoots(dirs, rootParentIdValue); List notRoots = (List) CollectionUtils.subtract(dirs, roots); for (Node root : roots) { root.setChildren(findChildren(root, notRoots)); } return roots; } /** * list to tree * 以没有父节点的节点作为根节点 * * @param dirs * @return */ public List buildCommonListToTree(List dirs) { List roots = findRoots(dirs, null); List notRoots = (List) CollectionUtils.subtract(dirs, roots); for (Node root : roots) { root.setChildren(findChildren(root, notRoots)); } return roots; } private List findRoots(List allNodes, Object rootParentIdValue) { List results = new ArrayList(); for (Node node : allNodes) { if ((isBlank(rootParentIdValue) && (isBlank(node.getParentId()) || "-1".equals(node.getParentId()))) || (isNotBlank(rootParentIdValue) && "-1".equals(node.getParentId()) && rootParentIdValue.equals(node.getParentId()))) { results.add(node); } } return results; } private List findRoots(List allNodes) { List results = new ArrayList(); for (Node node : allNodes) { boolean isRoot = true; for (Node comparedOne : allNodes) { if (isNotBlank(node.getParentId()) && node.getParentId().equals(comparedOne.getId())) { isRoot = false; break; } } if (isRoot) { results.add(node); } } return results; } private List findChildren(Node root, List allNodes) { List children = new ArrayList(); for (Node comparedOne : allNodes) { if (isNotBlank(comparedOne.getParentId()) && comparedOne.getParentId().equals(root.getId())) { children.add(comparedOne); } } List notChildren = (List) CollectionUtils.subtract(allNodes, children); for (Node child : children) { List tmpChildren = findChildren(child, notChildren); child.setChildren(tmpChildren); } return children; } private boolean isBlank(Object o) { return o == null || StringUtils.isBlank(o.toString()); } private boolean isNotBlank(Object o) { return !isBlank(o); } }