Skip to content

Instantly share code, notes, and snippets.

@andretietz
Last active November 17, 2020 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andretietz/3c956da0ec18ad597c63a23d83b9c4b3 to your computer and use it in GitHub Desktop.
Save andretietz/3c956da0ec18ad597c63a23d83b9c4b3 to your computer and use it in GitHub Desktop.
How to create a node tree from a node list using kotlin
data class Node(
val id: String,
val name: String,
val parentId: String? = null,
val childs: MutableList<Node> = mutableListOf()
)
// replace with:
//data class Node(
// val id: String,
// val name: String,
// val parentId: String? = null,
// val childs: List<Node>? = null)
/**
* +-1
* | +-3
* | +-4
* | +-5
* +-2
* +-6
*/
fun main() {
val init = listOf(
Node("1", "Node 1"),
Node("2", "Node 2"),
Node("3", "Node 3", "1"),
Node("4", "Node 4", "1"),
Node("5", "Node 5", "4"),
Node("6", "Node 6", "2"),
)
val tree = listToTree(init)
val list = treeToList(tree)
if (list.size == init.size) {
println("You've done it right!")
} else {
println("Nope, try it again!")
}
}
fun listToTree(list: List<Node>): List<Node> {
val mapTmp = list.map { it.id to it }.toMap().toMutableMap()
list.filter { it.parentId != null && mapTmp[it.parentId] != null }
.forEach { current ->
mapTmp[current.id] = current
mapTmp[current.parentId]?.childs?.add(current)
}
return mapTmp.values.filter { it.parentId == null }
}
fun treeToList(tree: List<Node>): List<Node> {
val flattenList = mutableListOf<Node>()
tree.forEach {
flattenList.add(Node(it.id, it.name, it.parentId))
it.childs.let { list ->
flattenList.addAll(treeToList(list))
}
}
return flattenList
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment