Home > Net >  How to get average of the specific value from list in Kotlin? (same as maxOf)
How to get average of the specific value from list in Kotlin? (same as maxOf)

Time:06-08

I have list of Location. Something like this:

[{"latitude": "45.42123", "longitude": "44.32132", "speed": 4.3}, {"latitude": "46.212", "longitude": "45.4334", "speed": 5.2}]

We have extensions in Kotlin so i can easily get max value of speed like this:

myList.maxOf { it.speed }

But how can i get average value of speed?

P.S. i found the same question in Java. I need solution in Kotlin.

CodePudding user response:

Try this:

val average = myList.map { it.speed }.average()

CodePudding user response:

You can do it like this

val average = myList.sumOf { it.speed } / myList.size
  • Related