How to do sum of elements for multiple list in kotlin

Viewed 5939

I want to combine two item list by sum of items group by it's count. object definition:Item (name:String, count:Long}

var list1 : MutableList<Item> = //From API 1 call
var list2 : MutableList<Item>= //From API 2 call

Example:

Item 1: [{"pen",2}, {"pencil", 3}]
Item 2: [{"pen",6}, {"chair", 2}]

Output like:

Final list: [{"pen",8}, {"pencil", 3},  {"chair", 2}]

How do I achieve in kotlin using any collection inbuilt function?

3 Answers

You will have to use groupBy and reduce:

val itemsCount = (list1 + list2)          // concat lists
    .groupBy { it.name }                  // group items by name
    .values                               // take list of values
    .map {                                // for each list
        it.reduce {                       // accumulate counts
            acc, item -> Item(item.name, acc.count + item.count)
        }
    }

You can add lists, group and then map values:

val l = list1 + list2
val r = l.groupBy { it.name }                   //Map<String, List<Item>>
    .mapValues { it.value.map { it.count }.sum() }    //Map<String, Long>
    .toList()                                   //List<Pair<String, Long>>
    .map { p -> Item(p.first, p.second) }
data class Product(val productId: String, val quantity: Double)

val groupedProducts = products
                .groupBy { it.productId }
                .values
                .map {
                    it.reduce {
                        accumulator, product ->
                            product.copy(quantity = accumulator.quantity + product.quantity)
                }
            }
Related