w3resource

Scala Programming: Count the number of occurrences of each element in a given list

Scala Programming List Exercise-22 with Solution

Write a Scala program to count the number of occurrences of each element in a given list.

Sample Solution:

Scala Code:

object Scala_List {    

  def list_elemnt_occurrences[A](list1:List[A]):Map[A, Int] = {
      list1.groupBy(el => el).map(e => (e._1, e._2.length))
    }  
  
  def main(args: Array[String]): Unit = {    
     println(list_elemnt_occurrences(List(1,1,1,2,2,3,6,4,4,6,1,6,2)))
     println(list_elemnt_occurrences(List("Red", "Green", "White", "Black", "Red", "Green", "Black")))
    }
}

Sample Output:

HashMap(1 -> 4, 6 -> 3, 2 -> 3, 3 -> 1, 4 -> 2)
HashMap(Black -> 2, Green -> 2, Red -> 2, White -> 1)

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to check whether a list contains a sublist.
Next: Write a Scala program to split a given list into two lists.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/scala-exercises/list/scala-list-exercise-22.php