Last active
November 17, 2020 08:46
-
-
Save andretietz/3c956da0ec18ad597c63a23d83b9c4b3 to your computer and use it in GitHub Desktop.
How to create a node tree from a node list using kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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