0

I have Map[String,String]so keys are distinct but most values are repeated. For example : Map[car-> "This is a car",truck-> "This is a car", fruit ->"This is a fruit"]

So it should return "This is a car" because it is repeated twice.

1
  • Should "This is a fruit" be returned if repeated?
    – korefn
    Commented Mar 8, 2013 at 5:56

4 Answers 4

6

I did something like this. Hope it helps.

val j = x.groupBy(_._2)

Then

j.maxBy(_._2.size)

Where x is your original map. The first call, returns a Map and then you just get the key value pair where the value (map , has max entries)

3
val m1 = Map("this" -> "that", "what" -> "that", "who" -> "me", "you" -> "who")
m1.groupBy(_._2).maxBy(_._2.size)
res0: ... = (that,Map(this -> that, what -> that))
1

Another solution

 map.values.groupBy(t => t ).values.maxBy(_.size).head
1
  • 1
    By the way, you don't need to define your own ( t => t ) function (thereby adding a class) -- Predef defines one for you. It's called "identity".
    – AmigoNico
    Commented Mar 8, 2013 at 12:01
0

Not the most elegant but my solution goes like

val list = Map(car-> "This is a car",truck-> "This is a car", fruit ->"This is a fruit")

list.map{
  case (k,v) => if(list.filter{case (key,value)=> value==v }.size>1)v
}.toSet

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.