Home > database >  Putting children in one list
Putting children in one list

Time:03-24

Please tell me how in such a data structure (simplified for better understanding) to bring all the children of the entity into one list:

    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>
)

I expect to see following result:

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

I try to use flatMap, but it did not lead to the expected result.

Thank you in advance!

CodePudding user response:

You can traverse the tree of Entities recursively like this:

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

Then you can call

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

to obtain the desired result.

CodePudding user response:

You could do it like this

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

and then

val result = listOfEntities.flatten()
  • Related