Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a custom object list in simple list in kotlin

Tags:

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?

like image 501
sagar suri Avatar asked May 01 '18 13:05

sagar suri


People also ask

How to sort a list of objects by one field in Kotlin?

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.

How to add list items in listview in Kotlin Android?

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.

How to convert one data type to another in Kotlin?

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:

How do I create a list with duplicate elements in Kotlin?

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.


2 Answers

You can use the map function:

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

This will map each ProductsResponse to it's ProductType.

like image 71
pixix4 Avatar answered Oct 18 '22 14:10

pixix4


val productNameList = productList.map { it.ProductType }

No need to specify type, it will be inferred

Check Higher-Order Functions and Lambdas

like image 24
JTeam Avatar answered Oct 18 '22 14:10

JTeam