How do I sum all the items of a list of integers in Kotlin?

You can use the .sum() function to sum all the elements in an array or collection of Byte, Short, Int, Long, Float or Double. (docs)

For example:

val myIntList = listOf(3, 4, 2)
myIntList.sum() // = 9

val myDoubleList = listOf(3.2, 4.1, 2.0)
myDoubleList.sum() // = 9.3

If the number you want to sum is inside an object, you can use sumOf to select the specific field you want to sum: (docs)

data class Product(val name: String, val price: Int)
val products = listOf(Product("1", 26), Product("2", 44))
val totalCost  = products.sumOf { it.price } // = 70

Note: sumBy was deprecated in Kotlin 1.5 in favour of sumOf.


The above answers are correct but, this can be another way if you also want to sum all integers, double, float inside a list of Objects

list.map { it.duration }.sum()

The above answer is correct, as an added answer, if you want to sum some property or perform some action you can use sumBy like this:

sum property:

data class test(val id: Int)

val myTestList = listOf(test(1), test(2),test(3))

val ids = myTestList.sumBy{ it.id } //ids will be 6

sum with an action

val myList = listOf(1,2,3,4,5,6,7,8,9,10)

val addedOne = myList.sumBy { it + 1 } //addedOne will be 65

Tags:

Kotlin