将 children 放在一个列表中

Putting children in one list

请告诉我如何在这样的数据结构中(简化以便更好地理解)将实体的所有 children 放入一个列表中:

    fun main() {
    val listOfEntities = listOf(
        Entity(
            name = "John",
            entities = listOf(
                Entity(
                    name = "Adam",
                    entities = listOf()
                ),
                Entity(
                    name = "Ivan",
                    entities = listOf(
                        Entity(
                            name = "Henry",
                            entities = listOf(
                                Entity(
                                    name = "Kate",
                                    entities = listOf(
                                        Entity(
                                            name = "Bob",
                                            entities = listOf()
                                        )
                                    )
                                )
                            )
                        )
                    )
                )
            )
        )
    )

    val result = listOfEntities.flatMap { it.entities }.map { it.name }
    println(result)
}

data class Entity(
    val name: String,
    val entities: List<Entity>
)

我希望看到以下结果:

[John, Adam, Ivan, Henry, Kate, Bob]

我尝试使用flatMap,但没有得到预期的结果。

提前致谢!

你可以像这样递归遍历实体树:

fun List<Entity>.flattenEntities(): List<Entity> =
    this + flatMap { it.entities.flattenEntities() }

那你可以打电话

val result = listOfEntities.flattenEntities().map { it.name }

获得想要的结果。

你可以这样做

fun List<Entity>.flatten(): List<String> {
    return flatMap { listOf(it.name) + it.entities.flatten()}
}

然后

val result = listOfEntities.flatten()