我希望按项目总和组合两个项目列表。对象定义:Item (name:String, count:Long}
var list1 : MutableList<Item> = //From API 1 call
var list2 : MutableList<Item>= //From API 2 call
示例:
Item 1: [{"pen",2}, {"pencil", 3}]
Item 2: [{"pen",6}, {"chair", 2}]
输出如:
Final list: [{"pen",8}, {"pencil", 3}, {"chair", 2}]
如何使用任何内置功能集合在kotlin中实现?
答案 0 :(得分:6)
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)
}
}
答案 1 :(得分:1)
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)
}
}
答案 2 :(得分:0)
您可以添加列表,分组然后映射值:
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) }