T.Simmari
T.Simmari

Reputation: 195

Scala groupBy for a list

I'd like to create a map on which the key is the string and the value is the number of how many times the string appears on the list. I tried the groupBy method, but have been unsuccessful with that.

Upvotes: 19

Views: 35044

Answers (3)

Neil Turner
Neil Turner

Reputation: 11

This also works:

scala> val l = List("abc","abc","cbe","cab")
val l: List[String] = List(abc, abc, cbe, cab)
                                                                                                                                                                                                                                                                
scala> l.groupBy(identity).map(x => (x._1, x._2.length))
val res1: Map[String, Int] = HashMap(cbe -> 1, abc -> 2, cab -> 1)

Upvotes: 1

Ramesh Maharjan
Ramesh Maharjan

Reputation: 41957

Suppose you have a list as

scala> val list = List("abc", "abc", "bc", "b", "abc")
list: List[String] = List(abc, abc, bc, b, abc)

You can write a function

scala> def generateMap(list: List[String], map:Map[String, Int]) : Map[String, Int] = list match {
     |       case x :: y => if(map.keySet.contains(x)) generateMap(y, map ++ Map(x -> (map(x)+1))) else generateMap(y, map ++ Map(x -> 1))
     |       case Nil => map
     |     }
generateMap: (list: List[String], map: Map[String,Int])Map[String,Int]

Then call the function as

scala> generateMap(list, Map.empty)
res1: Map[String,Int] = Map(abc -> 3, bc -> 1, b -> 1)

Upvotes: 1

Mahesh Chand
Mahesh Chand

Reputation: 3250

Required Answer

scala> val l = List("abc","abc","cbe","cab")
l: List[String] = List(abc, abc, cbe, cab)

scala> l.groupBy(identity).mapValues(_.size) 
res91: scala.collection.immutable.Map[String,Int] = Map(cab -> 1, abc -> 2, cbe -> 1)

Upvotes: 29

Related Questions