You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kotlin的数据类对象列表中使用IndexOf方法?

解决Kotlin中列表元素索引查找的问题

首先先修正你代码里的基础语法错误:

  • seriesData类定义时,arrayListOf()后面多了多余的{},且类的闭合括号缺失
  • 变量定义可以用更简洁的字符串模板,同时遵循Kotlin编码规范(类名大驼峰、优先用val)

修正后的基础代码如下:

fun main() {
    data class SeriesData( 
        var seriesName: String = "",
        var bookListEntries: MutableList<Int> = arrayListOf()
    )
    val mySeriesData: MutableList<SeriesData> = ArrayList()
    for (i in 0..5) {
        val myString = "series$i"
        mySeriesData.add(SeriesData(seriesName = myString, bookListEntries = ArrayList()))
    }
}

错误原因

mySeriesData是一个列表容器,不是单个SeriesData对象,列表本身没有seriesName属性,直接调用.seriesName自然会报未解析引用的错误。你需要遍历列表中的元素,判断元素的seriesName是否符合条件,再获取对应的索引。

解决方案

方案1:查找第一个匹配元素的索引

用Kotlin集合的indexOfFirst函数,直接传入判断逻辑,这是最常用的方式:

val targetIndex = mySeriesData.indexOfFirst { it.seriesName == "series2" }
println(targetIndex) // 输出:2

如果找不到匹配元素,该函数会返回-1。

方案2:查找所有匹配元素的索引

如果存在多个seriesName为"series2"的元素,可以用mapIndexed过滤出所有符合条件的索引:

val allTargetIndices = mySeriesData.mapIndexed { index, data ->
    if (data.seriesName == "series2") index else null
}.filterNotNull()
println(allTargetIndices) // 输出所有匹配元素的索引列表

内容的提问来源于stack exchange,提问作者MikeBrown

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 21:57:13