w3resource

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


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)

Go to:


PREV : 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.

Scala Code Editor :

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

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.