Calculate sum of all items in a List of Integers in Kotlin
This article explores different ways to calculate the sum of all items in a List of Integers in Kotlin.
1. Using sum() function
A simple solution to calculate the sum of all elements in a List is calling the sum() function. It is available for a list of all numeric data types. i.e, Int, Long, Float, Double, Byte, Short.
|
1 2 3 4 5 6 7 |
fun main() { val items = listOf(10, 20, 30) val sum = items.sum() println(sum) // 60 } |
To get the sum of a specific field inside a list of objects, you can use the sumBy() function. If the field is a double, use the sumByDouble() function:
|
1 2 3 4 5 6 7 8 9 |
data class Item(val name: String, val price: Int) fun main() { val items = listOf(Item("1", 10), Item("2", 20), Item("3", 30)) val costs = items.sumBy { it.price } println(costs) // 60 } |
Note that as of Kotlin 1.5, sumBy() function is deprecated. You should use the sumOf() function instead.
|
1 2 3 4 5 6 7 8 9 |
data class Item(val name: String, val price: Int) fun main() { val items = listOf(Item("1", 10), Item("2", 20), Item("3", 30)) val costs = items.sumOf { it.price } println(costs) // 60 } |
Alternatively, you can transform each object of the element to the corresponding field using the map() function. Finally, return the sum using the sum() function. This is especially useful to convert and sum other data types.
|
1 2 3 4 5 6 7 8 9 |
data class Item(val name: String, val price: Int) fun main() { val items = listOf(Item("1", 10), Item("2", 20), Item("3", 30)) val costs = items.map { it.price }.sum() println(costs) // 60 } |
2. Reduce operation
Another viable alternative is to perform a reduce operation on the list, to get the sum of all elements in it. A typical implementation of this approach would look like:
|
1 2 3 4 5 6 7 |
fun main() { val items = listOf(10, 20, 30) val sum = items.reduce { x, y -> x + y } println(sum) // 60 } |
3. Using summaryStatistics() function
If you need other statistics about the list elements like min, max, average, etc., consider using the summaryStatistics() function of the primitive stream.
|
1 2 3 4 5 6 7 |
fun main() { val items = listOf(10, 20, 30) val sum = items.stream().mapToInt { it }.summaryStatistics().sum println(sum) // 60 } |
4. Naive solution
Finally, you can calculate the sum of all elements in a List using a for-loop, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun getSum(items: List<Int>): Int { var sum = 0 for (i in items) { sum += i } return sum } fun main() { val items = listOf(10, 20, 30) val sum = getSum(items) println(sum) // 60 } |
That’s all about calculating the sum of all items in a List of Integers in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)