Write a Scala program to count the number of occurrences of each element in a given list.
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)
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Sample Output:
need an explanation for this answer? contact us directly to get an explanation for this answer