Find average of all items in a List in Kotlin
This article explores different ways to find the average of all items in a List in Kotlin.
1. Using average() function
The recommended solution to find an average value of elements in the collection is using the Iterable<T>.average() function. It can be called upon Int, Long, Double, Float, Byte, and Short data types. The following code example shows invocation for this function:
|
1 2 3 4 5 6 |
fun main() { val list = listOf(1, 2, 3, 4, 5) val avg = list.average() println(avg) // 3.0 } |
2. Using SummaryStatistics
If you don’t mind using the Java Stream API, you can get the arithmetic mean of the elements of the primitive stream using the summaryStatistics() function. It can be used to get other stats about the elements of this stream like min, max, sum, etc. The following example demonstrates this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun getAverage(list: List<Int>): Double { val stats = list.stream() .mapToInt { it } .summaryStatistics() return stats.average } fun main() { val list = listOf(1, 2, 3, 4, 5) val avg = getAverage(list) println(avg) // 3.0 } |
3. Using Loop
Finally, you can write our custom routine for this trivial task using a loop:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun getAverage(list: List<Int>): Double { var sum: Long = 0 for (i in list) { sum += i.toLong() } return if (list.isNotEmpty()) sum.toDouble() / list.size else 0.0 } fun main() { val list = listOf(1, 2, 3, 4, 5) val avg = getAverage(list) println(avg) // 3.0 } |
That’s all about finding the average of all items in a List 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 :)