nxcloud.foundation.core.util.TreeHelper.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of nxcloud-core-base Show documentation
Show all versions of nxcloud-core-base Show documentation
Base libraries for NXCloud Framework
package nxcloud.foundation.core.util
object TreeHelper {
/**
* 构建树
*/
@JvmStatic
fun buildTree(
list: List,
id: (T) -> ID,
parentId: (T) -> ID,
isTop: (ID) -> Boolean,
setChildren: (T, List) -> Unit,
sort: Comparator,
): List {
// 先排序
val sorted = list
.sortedWith(sort)
val map = sorted.associateBy(id)
val childrenMap = mutableMapOf>()
val tree = mutableListOf()
sorted
.forEach {
val parent = parentId(it)
if (isTop(parent)) {
// 如果是顶层 加入顶层节点
tree.add(it)
} else {
// 如果不是顶层 加入到父节点的子节点 父节点不存在的数据直接丢弃
map[parent]?.let { p ->
if (childrenMap[parent] == null) {
childrenMap[parent] = mutableListOf()
}
childrenMap[parent]!!.add(it)
}
}
}
// 回写 children
childrenMap
.forEach { (id, children) ->
map[id]?.let {
setChildren(it, children)
}
}
return tree.toList()
}
@JvmStatic
fun buildTree(
list: List,
id: (T) -> Long,
parentId: (T) -> Long,
setChildren: (T, List) -> Unit,
sort: Comparator,
): List {
return buildTree(list, id, parentId, { it == 0L }, setChildren, sort)
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy