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?
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With