I have a list of ParentObject. Foreach parentObject, it has 2 childObject. The image like that
val listParent: MutableList<ParentObject> = mutableList()
ParentObject {
ChildOjbect1{} // object1 can not be NULL
ChildOjbect2{} // object2 can be NULL
}
And, I want to build a mutableList of ChildObject.
val listChild: MutableList<ChildObject> = mutableList()
list.add(parentObject.childOjbect1) // Because childObj1 can not be null
parentOjbect.childObject2?.let { child ->
list.add(child)
}
Question:
I only need listChild with 6 items ( Basically I'd like to fixed size of listChild is 6 )
I am coding as below in Kotlin:
fun buildListChild(): List<ChildOjbect> {
val listChild // instance mutable listChild
forEach( parent: listParent) {
listChild.add(parent.childObject1)
parent.childOjbect2?.let { it ->
listChild.add(it)
}
return listChild.take(6)
}
I think performance is not good, because it loop in all of parent item.
Beside that I really don't want to always check size of listChild before add.
What is the best way to solve problem here ?
You can create List or Array with fixed size, but in that case you need to initialize it, as val childList = arrayOfNulls<ChildObject>(6)
(no other option to have an array with fixed size without initializing it), and in your loop check if it full (or when last element added) and return from method.
In that case yo don't need to loop over all parent elements and after to cut it, just do the simple check.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With