Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now