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

Kotlin如何将嵌套List<People>映射为List<List<Student>>

嵌套列表映射实现方案

首先先修正你提供的普通List转换函数的小问题——在map的lambda中,this指代的是外层的List<People>,而非单个People实例,所以应该用it来访问单个对象的属性:

fun List<People>.convert(): List<Student> {
    return this.map {
        Student(
            age = it.age,
            name = it.name
        )
    }
}

嵌套列表的两种转换方式

方式一:复用已有扩展函数

对于List<List<People>>,只需要对外层列表再做一次map,每个内层列表直接调用上面定义的convert()方法即可:

fun List<List<People>>.convertNested(): List<List<Student>> {
    return this.map { innerList -> innerList.convert() }
}

方式二:嵌套map直接转换

如果不想单独定义普通列表的扩展函数,也可以直接嵌套两层map一步完成转换:

fun List<List<People>>.convertNested(): List<List<Student>> {
    return this.map { innerList ->
        innerList.map { people ->
            Student(
                age = people.age,
                name = people.name
            )
        }
    }
}

使用示例

无论是哪种方式,调用起来都很简洁:

val peopleNestedList: List<List<People>> = // 你的嵌套People列表
val studentNestedList: List<List<Student>> = peopleNestedList.convertNested()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:50:29