Вы можете сгруппировать категории по их name
s, взять значения, reduce
их путем накопления их amount
s и отсортировать результат в конце.
См. Это:
data class Category(var name: String, var amount: Float)
fun main() {
var list = mutableListOf<Category>()
list.add(Category("apple", 100F))
list.add(Category("orange", 300F))
list.add(Category("banana", 400F))
list.add(Category("apple", 100F))
list.add(Category("banana", 300F))
list.add(Category("cherry", 100F))
// print the source list once in order to see differences in the output
println(list)
// group the items by name
val sortedList: MutableList<Category> =
list.groupBy { it.name }
// take the values
.values
// and map them
.map {
// by a reduction that
it.reduce {
// accumulates the amounts of items with the same name
acc, item -> Category(item.name, acc.amount + item.amount)
}
// and finally sort the resulting list by name
}.sortedWith(compareBy { it.name }).toMutableList()
// print the result
println(sortedList)
}
Это выводит
[Category(name=apple, amount=100.0), Category(name=orange, amount=300.0), Category(name=banana, amount=400.0), Category(name=apple, amount=100.0), Category(name=banana, amount=300.0), Category(name=cherry, amount=100.0)]
[Category(name=apple, amount=200.0), Category(name=banana, amount=700.0), Category(name=cherry, amount=100.0), Category(name=orange, amount=300.0)]
в Kotlin Playground.