Group the strings with occurrence count from a List using scala

Sudarshan Kasar
Feb 14, 2024

--

package exercise

import scala.collection.mutable

object UniqueElementsWithCount extends App {
/*
input - List(Student("abc"), Student("def"), Student("abc"))
case class Student(name: String)
o/p : Map("abc" -> 2, "def" -> 1)
*/

case class Student(name: String)

val list: List[Student] = List(Student("abc"), Student("def"), Student("abc"))


import scala.collection.mutable.Map
val counter = (students: Map[String, Int], student: Student) => if (students.contains(student.name)) {
val ss = students(student.name)
students += (student.name -> (ss + 1))
} else students += (student.name -> 1)

val studentsWithCount: mutable.Map[String, Int] = list.foldLeft(Map.empty[String, Int]) { (students, student) =>
if(students.contains(student.name)) {
val ss = students(student.name)
students += (student.name -> (ss + 1))
} else students += (student.name -> 1)
}
studentsWithCount map println

//clean code with functions
val studentsCountWithFunction = list.foldLeft(Map.empty[String, Int])(counter)
studentsCountWithFunction map println

}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sudarshan Kasar
Sudarshan Kasar

No responses yet

Write a response