/**
* List樹 -> 樹
* 核心
* ************
* 將數組型的JsonObjects轉成樹狀結構
* 注意,一定要排好順序那種
* 應用: cte語法查詢出父級子級的list,想轉化成樹
*
* @param nodes 數據源
* @param parentId 頂級的id(就是最頂層的parentId)
* @return
*/
public static JsonObjects toTree(JsonObjects nodes, Long parentId) {
//創建臨時組裝存儲空間
JsonObjects result = JsonObjects.VOID();
//如果存在原-List
if (CollectionUtils.isNotEmpty(nodes)) {
//如果不存在,給與默認值
if (parentId == null) {
parentId = nodes.get(0).getLong("parentId", 0);
}
//for循環
for (JsonObject node : nodes) {
//獲取原-list中的parentId
long thisParentId = node.getLong("parentId");
//對比父級id
if (thisParentId == parentId) {
//遞歸
JsonObjects children = toTree(nodes, node.getLong("id"));
//如果存在數據,組裝上
if (CollectionUtils.isNotEmpty(children)) {
node.append("children", children);
}
//驗證是否存在
if (!result.contains(node)) {
//不存在,存入
result.add(node);
}
}
}
}
return result;
}