package com.upchina.rbac.vo; import com.google.common.collect.Lists; import cn.hutool.core.util.StrUtil; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public interface IParentChildVO { PK getId(); PK getPid(); List getChildren(); void setChildren(List list); default void buildParent(IParentChildVO vo, Map allMap, Map rootMap) { PK pid = (PK) vo.getPid(); if (pid != null && ((pid instanceof String && StringUtils.isNotEmpty((String) pid) && !"0".equals(pid) && !"-1".equals(pid)) || (pid instanceof Integer && (Integer) pid > 0) || (pid instanceof Long && (Long) pid > 0))) { IParentChildVO parent = allMap.get(vo.getPid()); if (parent == null) return; List children = parent.getChildren(); if (children != null) { if (children.stream().noneMatch(child -> child.getId().equals(vo.getId()))) { children.add(vo); } } else { parent.setChildren(Lists.newArrayList(vo)); } buildParent(parent, allMap, rootMap); } else { rootMap.put((PK) vo.getId(), vo); } } default List buildTree(List voList, List allList) { Map allMap = allList.stream().collect(Collectors.toMap(vo -> (PK) vo.getId(), Function.identity())); Map rootMap = new HashMap<>(); voList.forEach(vo -> buildParent(vo, allMap, rootMap)); return Lists.newArrayList(rootMap.values()); } }