Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 845
Frank van der Linden Avatar asked Oct 17 '18 09:10

Frank van der Linden


People also ask

How do I make a list of numbers on Kotlin?

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.


2 Answers

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.

like image 111
David Miguel Avatar answered Sep 29 '22 20:09

David Miguel


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
like image 33
Cruces Avatar answered Sep 29 '22 21:09

Cruces