Hey i have nested list and i wanted to find last occurrence index value of outer list. I tried to search in Kotlin Doc. I tried some code but I failed. So how can I do this in my case in efficient way.
fun main() {
val value = listOf(
Group(0, mutableListOf(GroupValue(true, "1"))),
Group(1, mutableListOf(GroupValue(true, "2"))),
Group(2, mutableListOf(GroupValue(false, "3"))),
Group(3, mutableListOf(GroupValue(true, "4"))),
Group(4, mutableListOf(GroupValue(false, "5"))),
Group(5, mutableListOf(GroupValue(true, "6"))),
Group(6, mutableListOf(GroupValue(true, "6"), GroupValue(false, "7"))),
Group(7, mutableListOf(GroupValue(true, "6"), GroupValue(false, "7"))),
Group(8, mutableListOf(GroupValue(true, "6"), GroupValue(true, "7"), GroupValue(false, "7"))),
Group(9, mutableListOf(GroupValue(false, "6"), GroupValue(true, "7"))),
Group(10, mutableListOf(GroupValue(true, "7")))
)
val result = value.asSequence().flatMap { it.value }.indexOfLast { conversationItems ->
conversationItems?.isRead == false
}
println("result $result")
}
Group
data class Group(
val key: Int,
val value: MutableList<GroupValue?>
)
GroupValue
data class GroupValue(
val isRead: Boolean? = null,
val id: String? = null
)
Getting output of above code is
result 13
Expected Output
result 9
I don't know what i am doing wrong in above logic
CodePudding user response:
13 is correct since you used flatMap
, which turns all your lists into a single list and you're getting the index of an item in that bigger, combined list.
From what you said you expected, I'm guessing you want the index of the outer list for the last Group containing a false
isRead
GroupValue. I would do that like this:
val result = value.indexOfLast { group ->
group.value.any { it?.isRead == false }
}