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?
We can sort a List of Objects by one field by using sortBy (): sortBy {it.field} package com.bezkoder.kotlin.sortlist data class Date (val year: Int, val month: Int, val day: Int) { } You can use sortByDescending {it.field} for descending order.
An Adapter class is used to add the list items in the list. It bridges the list of data between an AdapterView with other Views components (ListView, ScrollView, etc.). Kotlin Android Custom ListView Example In this example, we will create a custom ListView and perform click action on list items.
In Kotlin, helper function can be used to explicitly convert one data type to another to another data type. The following helper function can be used to convert one data type into another: Note: There is No helper function available to convert into boolean type. Kotlin Program to convert the one data type into another:
Kotlin mutable or immutable lists can have duplicate elements. For list creation, use the standard library functions listOf () for read-only lists and mutableListOf () for mutable lists.
You can use the map function:
val productNameList:List<String> = productList.map { it.ProductType }
This will map each ProductsResponse to it's ProductType.
val productNameList = productList.map { it.ProductType }
No need to specify type, it will be inferred
Check Higher-Order Functions and Lambdas
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With