I have a list of custom objects. Below is the data class:

data class ProductsResponse(
        val id:String,
        val ProductType:String
)

I have a below list:

var productList: List<ProductResponse>

我希望输出为:

var productNameList: List<String>

我想得到一份只有ProductType人的名单,即Strings人中的list

I know using a for loop and copying the ProductType string to a new list will do the job. But I wanted to do it in a more shorter way using the power Kotlin provides.

How can I convert the above custom object list to a list of Strings in Kotlin way?

推荐答案

You can use the map function:

val productNameList:List<String> = productList.map { it.ProductType }

This will map each ProductsResponse to it's ProductType.

Kotlin相关问答推荐

当通过firstOrders访问时,存储在伴随对象中的对象列表具有空值

Kotlin和JavaFX:绑定行为奇怪

"Kotlin中的表达式

处理合成层次 struct 中的深层按钮以切换视图

如何在不基于数据 map 的情况下将图例添加到lets plot kotlin

Kotlin 函数名后面的大括号是什么意思?

Kotlin 获取继承类的默认 hashCode 实现

顶级属性的初始化

通过顺序多米诺骨牌操作列表管理对象的最佳方法是什么?

Kotlin 具体类从抽象类和接口扩展而来,接口使用抽象类中实现的方法

JavaFX - 你如何在 Kotlin 中使用 MapValueFactory?

在 Kotlin 中,::class.simpleName是做什么的?

Jetpack Compose – LazyColumn 不重组

如何获取Kotlin中变量的名称?

在android的默认浏览器 Select 列表中添加我的浏览器?

不推荐使用仅限生命周期的LifecycleEvent

Android:Exoplayer - ExtractorMediaSource 已弃用

Kotlin替换字符串中的多个单词

使用 java lambda 调用 kotlin 函数时,Kotlin 无法访问 kotlin.jvm.functions.Function1

如何在 Kotlin 中定义新的运算符?