I have a list of products and a list of types, but to know what type the product belongs to I need to rely on the ID in the type list, so I need to convert it to a new NewProducts list and its type is a String, not an Integer.
data class Product(val id:String,val name:String,val price:Float,val type:Int)
data class Type(val id:Int,val name:String)
corresponding to the above data is the JSON snippet below:
Products:
[
{
"id":1,
"name":"Product 1",
"price":3444,
"type":1
},
{
"id":2,
"name":"Product 2",
"price":3444,
"type":2
},
{
"id":3,
"name":"Product 3",
"price":3444,
"type":3
},
{
"id":4,
"name":"Product 4",
"price":3444,
"type":1
},
{
"id":5,
"name":"Product 5",
"price":3444,
"type":2
}
]
and Type model:
[
{
"id": 1,
"type": "A"
},
{
"id": 2,
"type": "B"
},
{
"id": 3,
"type": "C"
},
]
So I want to convert them to a new object like this:
data class NewProduct(val id:String,val name:String,val price:Float,val type:String)
It looks like:
var products = mutableListOf<Product>(
Product("1", "Product 1", 34f, 1),
Product("2", "Product 2", 34f, 2),
Product("3", "Product 3", 34f, 3),
Product("4", "Product 4", 34f, 1),
Product("5", "Product 5", 34f, 2),
)
var types = mutableListOf<Type>(
Type(1, "A"), Type(2, "B"),
Type(3, "C"),
)
// i want to convert to NewProduct list
products.map { products-> }
Can you help me with this problem?
2
Answers
You can do
You can first convert types into a map to access the types by
id
much faster:Then map the products
This way you can do it with O(n) complexity.