Lobsterrrr
Lobsterrrr

Reputation: 335

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.

Upvotes: 1

Views: 1004

Answers (1)

Tzach Zohar
Tzach Zohar

Reputation: 37832

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

Upvotes: 4

Related Questions