Kotlin高效查找嵌套列表中未读元素最后一次出现的内外层索引
解决方案
实现思路:从嵌套列表的末尾倒序遍历,外层列表从最后一个元素向前遍历,每个外层元素对应的内层列表同样从末尾向前遍历,找到第一个满足isRead != true的元素时直接返回对应索引,无需遍历剩余元素,性能最优。
实现代码
首先是你提供的数据结构定义:
data class Group( val key: Int, val value: MutableList<GroupValue?> ) data class GroupValue( val isRead: Boolean? = null, val id: String? = null )
查找函数实现:
fun findLastOccurrenceIndices(groups: List<Group>): Pair<Int, Int>? { // 外层列表倒序遍历 for (outerIndex in groups.indices.reversed()) { val innerList = groups[outerIndex].value // 内层列表倒序遍历 for (innerIndex in innerList.indices.reversed()) { val groupValue = innerList[innerIndex] // 匹配查找条件,自动覆盖GroupValue为null、isRead为null/false的情况 if (groupValue?.isRead != true) { return Pair(outerIndex, innerIndex) } } } // 未找到符合条件的元素时返回null,可根据需求调整默认返回值 return null }
测试验证
场景1测试
val scene1 = 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"))), ) val result1 = findLastOccurrenceIndices(scene1) result1?.let { println("inner list index is ${it.second} and outer list index is ${it.first}") } // 输出:inner list index is 0 and outer list index is 4
场景2测试
val scene2 = 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, "7"))) ) val result2 = findLastOccurrenceIndices(scene2) result2?.let { println("inner list index is ${it.second} and outer list index is ${it.first}") } // 输出:inner list index is 1 and outer list index is 6
内容的提问来源于stack exchange,提问作者Compose Learner
相关产品推荐
相关产品推荐

