Kotlin中如何简便替换列表中指定time的Exercize对象?
在Kotlin中替换列表中指定time的Exercize对象
首先假设你的Exercize是一个数据类(如果不是,只要保证time属性可访问即可):
data class Exercize(val time: Int, val name: String)
根据列表类型的不同,有两种简便实现方式:
1. 处理不可变List(生成新列表)
如果原列表是不可变的List,推荐用map函数遍历并生成新列表,这是Kotlin函数式风格的典型写法:
val originalList = listOf( Exercize(9, "pushup"), Exercize(10, "run"), Exercize(12, "swim") ) val newExercise = Exercize(10, "burpy") val updatedList = originalList.map { exercise -> if (exercise.time == newExercise.time) newExercise else exercise }
map会逐个检查列表元素,当元素的time和新对象匹配时,替换为新对象;否则保留原元素,最终返回一个包含修改结果的新列表。
2. 处理可变MutableList(修改原列表)
如果原列表是可变的MutableList,可以直接修改原列表,有两种简洁写法:
方式一:用replaceAll函数
replaceAll会遍历列表并直接替换每个元素,写法最简洁:
val mutableList = mutableListOf( Exercize(9, "pushup"), Exercize(10, "run"), Exercize(12, "swim") ) val newExercise = Exercize(10, "burpy") mutableList.replaceAll { exercise -> if (exercise.time == newExercise.time) newExercise else exercise }
方式二:用forEachIndexed定位替换
如果需要更明确地控制索引位置,可以用forEachIndexed:
mutableList.forEachIndexed { index, exercise -> if (exercise.time == newExercise.time) { mutableList[index] = newExercise } }
内容的提问来源于stack exchange,提问作者Bo Z
相关产品推荐
相关产品推荐

