Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do sum of elements for multiple list in kotlin

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?

like image 377
bNd Avatar asked Dec 24 '22 14:12

bNd


1 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)
        }
    }
like image 125
Alberto S. Avatar answered Dec 27 '22 02:12

Alberto S.