Skip to main content

How to find the average of elements in an ArrayList in Kotlin

How to find the average of elements in an ArrayList in Kotlin.

Here's a step-by-step tutorial on how to find the average of elements in an ArrayList in Kotlin:

  1. First, create an ArrayList and add elements to it:
val numbers = arrayListOf(10, 20, 30, 40, 50)
  1. Next, calculate the sum of all the elements in the ArrayList using the sum() function:
val sum = numbers.sum()
  1. Get the size of the ArrayList using the size property:
val size = numbers.size
  1. Calculate the average by dividing the sum by the size:
val average = sum.toDouble() / size
  1. Finally, print the average:
println("The average is: $average")

Here's the complete code:

fun main() {
val numbers = arrayListOf(10, 20, 30, 40, 50)
val sum = numbers.sum()
val size = numbers.size
val average = sum.toDouble() / size
println("The average is: $average")
}

Output:

The average is: 30.0

Alternatively, you can also use the average() function provided by Kotlin's standard library to directly calculate the average of the elements in the ArrayList:

fun main() {
val numbers = arrayListOf(10, 20, 30, 40, 50)
val average = numbers.average()
println("The average is: $average")
}

Output:

The average is: 30.0

That's it! You now know how to find the average of elements in an ArrayList in Kotlin.