50 lines
1.8 KiB
Java
50 lines
1.8 KiB
Java
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<T extends IParentChildVO, PK> {
|
|
|
|
PK getId();
|
|
|
|
PK getPid();
|
|
|
|
List<T> getChildren();
|
|
|
|
void setChildren(List<T> list);
|
|
|
|
default void buildParent(IParentChildVO vo, Map<PK, IParentChildVO> allMap, Map<PK, IParentChildVO> 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<IParentChildVO> 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<? extends IParentChildVO> buildTree(List<? extends IParentChildVO> voList, List<? extends IParentChildVO> allList) {
|
|
Map<PK, IParentChildVO> allMap = allList.stream().collect(Collectors.toMap(vo -> (PK) vo.getId(), Function.identity()));
|
|
Map<PK, IParentChildVO> rootMap = new HashMap<>();
|
|
voList.forEach(vo -> buildParent(vo, allMap, rootMap));
|
|
return Lists.newArrayList(rootMap.values());
|
|
}
|
|
}
|