skip to Main Content

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


  1. You can do

    products.map { product ->
        NewProduct(
            product.id,
            product.name,
            product.price,
            types.first { type -> type.id == product.type }.name
        )
    }
    
    Login or Signup to reply.
  2. You can first convert types into a map to access the types by id much faster:

    val typeMap: Map<Int, String> = types.associateBy(Type::id, Type::name)
    
    // {1=Type(id=1, name=A), 2=Type(id=2, name=B), 3=Type(id=3, name=C)}
    

    Then map the products

    val productsByType: List<NewProduct> = products.map {
            NewProduct(
                id = it.id,
                name = it.name,
                price = it.price,
                type = typeMap[it.type] ?: ""
            )
        }
    
    /**
    [NewProduct(id=1, name=Product 1, price=3444.0, type=A), 
     NewProduct(id=2, name=Product 2, price=3444.0, type=B), 
     NewProduct(id=3, name=Product 3, price=3444.0, type=C), 
     NewProduct(id=4, name=Product 4, price=3444.0, type=A), 
     NewProduct(id=5, name=Product 5, price=3444.0, type=B)]
    
    */
    

    This way you can do it with O(n) complexity.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search