Reputation: 160
I have a json value which i have read into nested case class. From this i need a scala map of (category,rating).Please help.
Expected output:
Map("MTH1"-> "9A","MTH2"-> "9B","SCI1" -> "8A")
Note: If any value is none, then it should be omitted.
Need some elegant and smart way to convert the values into scala Map
val myVal: List[myClass] = List(myClass("Tim", "100", Some("hills"),
List(subject("geometry", Some("MTH1"), Some("9A")),
subject("trigonometry", Some("MTH2"), Some("9B")),
subject("physics", Some("SCI1"), Some("8A"))
)))
case class myClass(
name: String,
classId: String,
teacher: Option[String],
subjects: List[subject]
)
case class subject(
name: String,
category: Option[String],
rating: Option[String]
)
myVal.foreach(i =>
(
i.subjects.foreach(
j => println(j.category.get, j.rating.get)
)))
Upvotes: 1
Views: 237
Reputation: 51271
The will return a List[Map[String,String]]
:
myVal.map(_.subjects
.collect{
case subject(_,Some(cat),Some(rat)) => cat -> rat
}.toMap)
Each element of the original List
is turned into a Map
of category -> rating
(key -> value) pairs.
Upvotes: 4