public static List getTreeList(String topId, List entityList) {
//存储顶层的数据
List resultList = new ArrayList<>();
Map<Object, OperatingStatementDto> treeMap = new HashMap<>(16);
for (int i = 0; i < entityList.size() && !entityList.isEmpty(); i++) {
OperatingStatementDto itemTree = entityList.get(i);
//把所有的数据放到map当中,pid为key
treeMap.put(itemTree.getNid(), itemTree);
//把顶层数据放到集合中
if (topId.equals(Integer.toString(itemTree.getPid())) || itemTree.getPid() == null) {
resultList.add(itemTree);
}
}
// 循环数据,把数据放到上一级的childen属性中
for (int i = 0; i < entityList.size() && !entityList.isEmpty(); i++) {
OperatingStatementDto itemTree = entityList.get(i); // 在map集合中寻找父亲
OperatingStatementDto data = treeMap.get(itemTree.getPid());
// 判断父亲有没有
if (data != null) {
if (data.getChildren() == null) {
data.setChildren(new ArrayList<>());
}
// 把子节点 放到父节点childList当中
data.getChildren().add(itemTree);
// 把放好的数据放回map当中
treeMap.put(itemTree.getPid(), data);
}
}
return resultList;
}