android filtering in a recursive model

47 views Asked by At

I have a model like below

data class BaseModel(
    val title: String,
    val number: Int,
    val items: List<BaseModel>? = null
)

and this model is generated as

fun generateModel(): List<BaseModel> {
    val childItem1 = BaseModel("child1", 1)
    val childItem2 = BaseModel("child2", 2)
    val childItem3 = BaseModel("child3", 3)
    val childItem4 = BaseModel("child4", 4)
    val childItem5 = BaseModel("child5", 5)
    val childItem6 = BaseModel("child6", 6)
    val childItem7 = BaseModel("child7", 7)
    val childItem8 = BaseModel("child8", 8)

    val childList1 = arrayListOf(childItem1, childItem2, childItem3)
    val childList2 = arrayListOf(childItem4, childItem5)
    val childList3 = arrayListOf(childItem6, childItem7, childItem8)

    val parentItem1 = BaseModel("parent1", 11, childList1)
    val parentItem2 = BaseModel("parent2", 22, childList2)
    val parentItem3 = BaseModel("parent3", 33, childList3)

    return arrayListOf(parentItem1, parentItem2, parentItem3)
}

How do I filter the BaseModel object whose number is 7 from this array? [ title: "parent3", number: 33, items: [ title: "child7", number: 7, items: null ] ]

I tried many ways using map and filter but could not reach the result.

1

There are 1 answers

0
Viacheslav Smityukh On

If you need to use a common functions like filter you have to make you array flat.

You can do something like this:

fun BaseModel.flat(): Sequence<BaseModel> = sequence {
    yield(this@flat)
    if ([email protected] != null) {
        for (model in [email protected]) {
            yieldAll(model.flat())
        }
    }
}

val array = arrayOf<BaseModel>()

array
    .flatMap { model -> model.flat() }
    .filter { model -> model.number == 7 }