Henrique Tavolaro
Henrique Tavolaro

Reputation: 571

How can I groupby and sum items from a list in Kotlin

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>?>

Upvotes: 2

Views: 2093

Answers (2)

det0
det0

Reputation: 281

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) }

Upvotes: 1

rahul.taicho
rahul.taicho

Reputation: 1379

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.

Upvotes: 1

Related Questions