Lobsterrrr Lobsterrrr - 1 month ago 7
Scala Question

How to find most frequent string in List of strings

I have a list of strings (

List[String]
) and I want to obtain the most frequent string from this list:

val list1 = List('a','a','0','b','b','a')


The answer should be:

freq_list1 = a


I was thinking to use
list1.sliding(2).count...
in order to get the count of unique string, but I don't know how to wrap it into finding the most frequent string.

Answer
list1.groupBy(identity).mapValues(_.size).maxBy(_._2)._1

EDIT: See comment below, can be made shorter by using maxBy(_._2.size) without mapping beforehand, thanks @kawty

Comments