Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the mode value of a list?

Is there a function in scala collections to find the max number of occurrence of a value in a list,

Lets say I have a list

L = List("A","B","B","E","B","E","B","B","C","E","B")

output: "B". 

I can write a module to calculate this, but I would expect there should be a scala "way" or scala collection function to do this, already. Thanks!

like image 688
Learner Avatar asked Mar 21 '23 11:03

Learner


1 Answers

I don't know of a ready-made way to do it, but this is how I would do it:

l.groupBy(i => i).mapValues(_.size).maxBy(_._2)._1

Oh, but note this doesn't handle the case where the mode is not unique!

like image 181
joescii Avatar answered Mar 29 '23 17:03

joescii