2

I have a list of dataClass OrderInProgress and I need to sum the prices of similar products and count them to return a list of CartDetail, similar to the query from room database. How can I do it?

@Entity(tableName = "order_in_progress")
data class OrderInProgress(

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    var id: Int = 0,
    @ColumnInfo(name = "product")
    var product: String,
    @ColumnInfo(name = "price")
    var price: Double
)
data class CartDetail(
    
    @ColumnInfo(name = "product")
    val product: String,
    @ColumnInfo(name = "sum_price")
    val sumPrice: Double,
    @ColumnInfo(name = "product_count")
    val productCount: Int
    
)

this is the room query

 @Query(
        "SELECT product, SUM(price) as sum_price, COUNT(product) as product_count " +
                "FROM order_in_progress GROUP BY product"
    )
    fun getCart(): Flow<List<CartDetail>?>

2 Answers2

1

If you have a list of OrderInProgress-Instances called 'orderInProgressList', you should be able to generate the related list of CartDetails by using the following code.

val cartDetailList = orderInProgressList
  .groupBy { it.product }
  .map { CartDetail(it.key, it.value.sumOf { it.price }, it.value.size) }
det0
  • 281
  • 2
  • 5
0

Try the following snippet:

fun getCartDetails(orders: List<OrderInProgress>): List<CartDetail> {
    return orders.groupBy { it.product }.map { entry ->
        val productType = entry.key
        val products = entry.value

        CartDetail(
            productType,
            products.map { it.price }.reduce { acc, price -> acc + price },
            products.size
        )
    }
}

It uses group by to associate similar products into a map of type Map<String, List<OrderDetails>> and then maps each entry to a CartDetail which uses a reducer function to sum the price for similar products.

rahul.taicho
  • 1,339
  • 1
  • 8
  • 18