Scala groupBy for a list

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)

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)

Tags:

List

Scala