Reputation: 4731
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>
I want the output as:
var productNameList: List<String>
I want to get a list which consist of only ProductType
i.e a list
of Strings
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?
Upvotes: 17
Views: 22978
Reputation: 146
val productNameList= productList.groupBy { it.ProductType }.keys
This is the exactly what you wanted.
Upvotes: 0
Reputation: 1505
val productNameList = productList.map { it.ProductType }
No need to specify type, it will be inferred
Check Higher-Order Functions and Lambdas
Upvotes: 12