I have a list of integers, like:
val myList = listOf(3,4,2)
Is there any quick way in Kotlin to sum all the values of the list? or do I have to use a loop?
Thanks.
To define a list of integers in Kotlin, call listOf() function and pass all the integers as arguments to it. listOf() function returns a read-only List. Since, we are passing integers for elements parameter, listOf() function returns a List<Int> object.
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 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
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