Max
Max

Reputation: 2552

How to get a List of Maps from a List of Objects in Scala

I need some help with Scala. I really have troubles in understanding how to deal with collections. What I have to do is traversing a List like this

List( MyObject(id, name, status), ..., MyObject(id, name, status) )

and getting another List like this one

List( Map("key", id1), Map("key", id2), ..., Map("key", idN) )

Notice that the 'key' element of all the maps have to be the same

Thanks

Upvotes: 0

Views: 339

Answers (2)

Ren
Ren

Reputation: 3455

I think this should do it.

list map { x => Map( "key" -> x.id ) }

An example

scala> case class Tst (fieldOne : String, fieldTwo : String)
defined class Tst

scala> val list = List(Tst("x", "y"), Tst("z", "a"))
list: List[Tst] = List(Tst(x,y), Tst(z,a))

list map { x => Map( "key" -> x.fieldOne ) }
res6: List[scala.collection.immutable.Map[String,String]] = List(Map(key -> y), Map(key -> a))

Upvotes: 0

Septem
Septem

Reputation: 3622

you can use the map function to transform a list of MyObject to a list of Map by:

val list = List( MyObject(id, name, status), ..., MyObject(id, name, status) )
val result = list map {o => Map("key" -> o.id)}

scala school from twitter is a good reading for beginners, and if you want to know the architecture of the Scala collections framework in detail, please refer to scala doc

Upvotes: 1

Related Questions