sagar suri
sagar suri

Reputation: 4731

Converting a custom object list in simple list in kotlin

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

Answers (3)

Vatsalengg
Vatsalengg

Reputation: 146

val productNameList= productList.groupBy { it.ProductType }.keys

This is the exactly what you wanted.

Upvotes: 0

JTeam
JTeam

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

pixix4
pixix4

Reputation: 1351

You can use the map function:

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

This will map each ProductsResponse to it's ProductType.

Upvotes: 59

Related Questions