Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn a list of objects into a map of two fields in Scala

I'm having a real brain fart here. I'm working with the Play Framework. I have a method which takes a map and turns it into a HTML select element. I had a one-liner to take a list of objects and convert it into a map of two of the object's fields, id and name. However, I'm a Java programmer and my Scala is weak, and I've only gone and forgotten the syntax of how I did it.

I had something like

organizations.all.map {org => /* org.prop1, org.prop2 */ }

Can anyone complete the commented part?

like image 894
evanjdooner Avatar asked Aug 19 '13 16:08

evanjdooner


1 Answers

I would suggest:

map { org => (org.id, org.name) } toMap

e.g.

scala> case class T(val a : Int, val b : String)
defined class T

scala> List(T(1, "A"), T(2, "B"))
res0: List[T] = List(T(1,A), T(2,B))

scala> res0.map(t => (t.a, t.b))
res1: List[(Int, String)] = List((1,A), (2,B))

scala> res0.map(t => (t.a, t.b)).toMap
res2: scala.collection.immutable.Map[Int,String] = Map(1 -> A, 2 -> B)
like image 97
Brian Agnew Avatar answered Sep 19 '22 18:09

Brian Agnew