ant2009
ant2009

Reputation: 22486

Finding an item in a list of lists that can contain many levels

kotlin 1.4.72

I have the following class that contains a list. However, the list will contain another list and could be 3 or 4 levels deep.

I am populating the data structure like this. And have a method to find a item from one of the children.

data class Producer(
        val id: Int,
        val children: List<Producer> = emptyList(),
) {
    fun createProducer(src: Producer): Producer {
        return Producer(
                id = src.id,
                children = src.children.map {
                    createProducer(it)
                }
        )
    }

    fun findProducerByIDorNull(id: Int): Producer? {
        val producer = children.firstOrNull {
            it.id == id
        }

        return producer
    }
}

Currently I am using firstOrNull. However, that will only find the item in the 1st level. If the item is at a 3 level it will return null.

Just wondering if there is a better way to do this.

Many thanks for any suggestions,

Upvotes: 1

Views: 78

Answers (1)

Joffrey
Joffrey

Reputation: 37680

You could make findProducerByIDOrNull recursive. Something like:

    fun findProducerByIDorNull(id: Int): Producer? {
        if (this.id == id) {
            return this
        }
        return children.asSequence()
            .mapNotNull { it.findProducerByIDorNull(id) }
            .firstOrNull()
    }

Upvotes: 2

Related Questions