Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala groupBy for a list

Tags:

list

scala

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.

like image 897
T.Simmari Avatar asked Nov 16 '17 10:11

T.Simmari


People also ask

How to use groupBy in scala?

Scala groupBy is used for grouping of elements based on some criteria defined as a predicate inside the function. This function internally converts the collection into map object and this map object work on key value pair. This is basically used for storing and retrieving of the elements.

How do I convert a list to map in Scala?

To convert a list into a map in Scala, we use the toMap method. We must remember that a map contains a pair of values, i.e., key-value pair, whereas a list contains only single values. So we have two ways to do so: Using the zipWithIndex method to add indices as the keys to the list.


1 Answers

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)
like image 98
Mahesh Chand Avatar answered Sep 21 '22 11:09

Mahesh Chand