1. Overview
The average of a list of numbers indicates a central point in a data set. Further, finding the average has many practical use cases when analyzing data and generating reports.
In this tutorial, we’ll explore multiple ways to find the average of all items in a list in Kotlin.
2. Using Loops
In this section, we’ll learn how to use loop constructs to solve our use case.
2.1. With for Loop
Let’s write the averageUsingForLoop() function that uses a for loop to iterate over the numbers list for computing the average:
fun averageUsingForLoop(numbers: List<Int>): Double {
var sum = 0.0
for (num in numbers) {
sum += num
}
val average = sum / numbers.size
return average
}
Next, let’s define the numbers list with a few sample integer values:
val numbers = listOf(10, 2, 3, 40, 5)
We’ll reuse the numbers list to validate all our approaches.
Lastly, let’s test the averageUsnigForLoop() function:
val average: Double = averageUsingForLoop(numbers)
assertEquals(12.0, average)
Great! We got this one right.
2.2. With forEach Loop
Similar to the for loop approach, let’s write the averageUsingForEachLoop() function that uses a forEach construct:
fun averageUsingForEachLoop(numbers: List<Int>): Double {
var sum = 0.0
numbers.forEach { sum += it }
val average = sum / numbers.size
return average
}
Like earlier, let’s verify our function:
val average: Double = averageUsingForEachLoop(numbers)
assertEquals(12.0, average)
It works as expected.
3. Using Extension Functions
In this section, we’ll explore a set of extension functions with lists to calculate the average.
3.1. With average()
Let’s use the average() extension function to calculate the average of all items of the numbers list:
val average: Double = numbers.average()
Now, let’s verify that it’s working correctly:
assertEquals(12.0, average)
Great! It works!
3.2. With sumByDouble()
We can also use the sumBy() extension function. Let’s use it in the averageUsingSumByDouble() function:
fun averageUsingSumByDouble(numbers: List<Int>): Double {
val sum = numbers.sumByDouble { it.toDouble() }
val average = sum / numbers.size
return average
}
It’s interesting to note that we used the it identifier to specify that we must use each element from the list.
Next, let’s confirm that it’s giving the right results:
val average: Double = averageUsingSumByDouble(numbers)
assertEquals(12.0, average)
3.3. With fold()
Now, let’s use the fold() extension function within the averageUsingFold() function to find the average:
fun averageUsingFold(numbers: List<Int>): Double {
val sum = numbers.fold(0.0) { acc, num -> acc + num }
val average = sum / numbers.size
return average
}
We must note the initial value of the accumulator (acc) is 0.0, and we add each number (num) to update the accumulator value.
Like earlier, let’s verify our function:
val average: Double = averageUsingFold(numbers)
assertEquals(12.0, average)
3.4. With reduce()
Let’s see how we can write the averageUsingReduce() function that uses the reduce() extension function on the numbers list:
fun averageUsingReduce(numbers: List<Int>): Double {
val sum = numbers.reduce { acc, num -> acc + num }
val average = sum.toDouble() / numbers.size
return average
}
It’s worth noting that reduce() is almost similar to fold(), except that the initial value is set as the first member of the list.
Further, let’s see this in action:
val average: Double = averageUsingReduce(numbers)
assertEquals(12.0, average)
Fantastic! It looks like we nailed this one.
4. Using Sequence
For large data sets, we can use the asSequence() method to wrap the list in a sequence. It’s required to access the elements of the list lazily and avoid the creation of any intermediate collection during transformations.
Let’s write the averageUsingSequence() function to compute the average of the numbers list by using the map() and sum() functions:
fun averageUsingSequence(numbers: List<Int>): Double {
val sum = numbers.asSequence().map { it.toDouble() }.sum()
val average = sum / numbers.size
return average
}
Now, we should also test this approach:
val average: Double = averageUsingSequence(numbers)
assertEquals(12.0, average)
Perfect! Our approach worked fine.
5. Conclusion
In this article, we learned several approaches, such as loops, extension functions, and sequences, to calculate the average of all items in a list in Kotlin.
As always, the code from this article is available over on GitHub.