user1668653
user1668653

Reputation: 237

Regarding FoldLeft with list and map in scala

I have a list of strings as json messages and i need to write to object from json using json4s.After parsing i need to store the object and objects attribute as key in a Map. Using var approach i am able to do that .But i do not want to use var and would like to use foldLeft to do the same.

Definition of class:

case class Definition
{
   name:String,
   status:String
}

sample json:

{"name":"test",
"status":"Enabled"
}

Using json4s read api i am getting the object as below.

Definition(test,Enabled)

i will get lit objects like above.From this list i need to create a map and need to store object.name as key and object as value.

Looking for optimized approach.

Upvotes: 1

Views: 522

Answers (1)

Sergii Lagutin
Sergii Lagutin

Reputation: 10681

// define case class
case class Definition(name: String, status: String)

// read objects from json
// i use test data to simplify example
val list = List(
  Definition("name1", "status1"),
  Definition("name2", "status2"),
  Definition("name3", "status3")
)

// transform list to map
list.map(d => d.name -> d).toMap  

To convert from json you can use:

val objectList = definitionList
  .foldLeft(List.empty[Definition])((listObject,result) => listObject :+ read[Definition](result))

or:

definitionList.map(read[Definition])

Upvotes: 2

Related Questions