score:4

Accepted answer

you can calculate the average of the second elements of the list of tuples, you don't need to do the sum yourself because scala has a builtin function for that. first we need to transform the list of tuples to a list of int values, we can do that using the map function as shown below

val average = list.map(_._2).sum/list.size.todouble

now you have the average, you can filter your list based on its value

val newlist = list.filter(_._2  < average)

note that we didn't remove anything from the list, we created a new one with filtered elements

score:1

you can do:

val sum = list.map(_._2).sum
val avg: double = sum / list.size.todouble

val filtered = list.filter(_._2 > avg)

note this is traversing the list twice, once for summing and once for filtering. another thing to note is that scala list[t] is immutable. when you filter, you're creating a new list object with the filtered data.

score:1

val average = list.map(_._2).sum / list.size.todouble
list.filter(p => p._2 >= average)

you need to cast to double, else average would be cast to an int and be imprecise. the filter only keeps the element greater than the average.


Related Query

More Query from same tag