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

基于函数结果更新列表所有元素的Kotlin实现问询

基于函数结果批量更新列表元素

网络及Stack Overflow上有大量相关示例,但我观察到大多是基于索引实现的。我希望通过单个函数的结果来更新列表中的所有元素,以下是我的简化版本代码:

data class Person(val id: Int, val name: String)

var tempList: List<Pair<Person, Boolean?>> = emptyList()

val personList = listOf(Person(1, "1"), Person(2, "2"), Person(3, "3"))

fun processPerson(person: Person): Boolean {    
    return person.name == "1"
}

fun main() {
    tempList = personList.map { item ->
        Pair(item, null)
    }
    
    tempList.forEach { item ->
        println(processPerson(item.first))
    }
}

我期望得到的更新后列表为:

listOf(Pair(Person(1, "1"), true), Pair(Person(2, "2"), false), Pair(Person(3, "3"), false))

解决方案

不需要先将Pair的第二个元素初始化为null再遍历处理,直接在map转换时调用processPerson函数生成对应结果即可,一步到位:

fun main() {
    tempList = personList.map { person ->
        Pair(person, processPerson(person))
    }
    
    // 验证结果
    tempList.forEach { println(it) }
}

这样处理后,tempList就会直接生成你期望的结构——每个Person对象和对应的processPerson函数返回值组成Pair,无需额外的遍历更新步骤,代码更简洁高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 16:05:03