14

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.

3 Answers3

26

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
David Miguel
  • 6,915
  • 3
  • 42
  • 48
13

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
Cruces
  • 2,199
  • 1
  • 14
  • 40
6

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()
Erick
  • 113
  • 2
  • 5