Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
Putting children in one list

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!

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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()
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda