I have a list, each element of which contains an inner list. I need to get an element of the outer list, in which the specified condition is fulfilled for the inner list at least once. I wrote code like this:
outerList?.find {
!it.items.isNullOrEmpty() && it.items?.any { item ->
item.isVisible == visibility &&
item.progress == currentProgress
} == true
}?.let { outerItem ->
currentItem = outerItem
// here some logic
} ?: run {
currentItem = null
// here some logic
}
But I'm not sure if this code is efficient. Perhaps you should use sequences instead of a list? Can you please tell me which solution will be the most efficient in terms of execution time and memory consumption for my case?
CodePudding user response:
A sequence isn't going to help here, because you are only performing one operation on the outer list, and one operation on the inner list.
Your !it.items.isNullOrEmpty()
check is entirely redundant to the ?.any
you follow it up with, so you can remove that. Perhaps the cleanest way to write this would be:
outerList?.find {
it.items.orEmpty().any { item ->
item.isVisible == visibility && item.progress == currentProgress
}
}
Never do this: ?.let { ... } ?: run { }
. Aside from being very poor for readability, it is error-prone. If you accidentally return null from the let
block, the run
block will also be run unexpectedly.