0

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Will that work? Doesn't map need to take in a function that returns something?
0

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))

1 Comment

Thank you, it works! It was so simple... My mistake was using a comma between the key and the value instead of the "arrow" symbol, that's why the compiler got angry!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.