问题
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!
回答1:
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!
回答2:
This gives you the mode:
import scala.collection.breakOut
import scala.collection.generic.CanBuildFrom
def mode
[T, CC[X] <: Seq[X]](coll: CC[T])
(implicit o: T => Ordered[T], cbf: CanBuildFrom[Nothing, T, CC[T]])
: CC[T] = {
val grouped = coll.groupBy(x => x).mapValues(_.size).toSeq
val max = grouped.map(_._2).max
grouped.filter(_._2 == max).map(_._1)(breakOut)
}
回答3:
Get all the modes of the list (without RDD):
val grouped = L.groupBy(i => i).map(kv => (kv._1, kv._2.size))
val modeValue = grouped.maxBy(_._2)._2
val modes = grouped.filter(kv => kv._2 == modeValue).map(_._1)
来源:https://stackoverflow.com/questions/21998521/how-to-find-the-mode-value-of-a-list