Rpant
Rpant

Reputation: 1054

groupBy on String in Scala

I am doing a groupBy on a string as follows: "message".groupBy("message".count(_.toChar)) I was expecting it to yield a map as: {1 => "mag" , 2 => "es"} However the above code doesn't even compile , where am I going wrong. I want to produce a map based on the discriminator function count of chars.

Upvotes: 1

Views: 1351

Answers (1)

akuiper
akuiper

Reputation: 214957

You can do:

("message".groupBy(identity).mapValues(_.size)
 .groupBy(_._2).mapValues(_.foldLeft("")(_+_._1)))

// res8: scala.collection.immutable.Map[Int,String] = Map(2 -> es, 1 -> amg)

Upvotes: 1

Related Questions