Home > Enterprise >  Create Map from Elements from List of case class
Create Map from Elements from List of case class

Time:05-14

      case class Student(id:String, name:String, teacher:String )
      val myList = List( Student("1","Ramesh","Isabela"), Student("2","Elena","Mark"),Student("3","invalidKey","Someteacher"))
      
      val a = myList.foreach( i=> (i.name ->  i.teacher)).toMap.filter(i.name != "invalidKey")

I have a list of case class of student. I Want to build a map of student, teacher which are name ( key of the map) will always be unique. Preferably map can filter out a certain name.

CodePudding user response:

You're using foreach, which returns Unit as the result. I would suggest either of these 2 below. First one is as Luis Miguel mentioned:

val myMap = myList.collect {
  case student if student.name != "invalidKey" => student.name -> student.teacher
}.toMap

Or:

val myMap2 = myList.foldLeft[Map[String, String]](Map.empty) {
  case (elementsMap, newElement) if newElement.name != "invalidKey" => 
    elementsMap   (newElement.name -> newElement.teacher)
  case (elementsMap, _) => elementsMap
}

Differences:

First approach is much easier to read and shorter (being shorter is not an advantage though :D). Second one has less iterations (first one has another iteration to convert to Map).

  • Related