Mr.Turtle
Mr.Turtle

Reputation: 3090

Convert Scala Array[Object] to Map

I have an array with objects (Array[Organisation]). The Organisation object contains a long orgId and a string orgName.

Is there a convenient way of converting this into a Map[Long, String] (orgId, orgName)

case class OrgRegistryConfig() {

  var organisations: Array[Organisation] = _

  def toMap() : Map[Long, String] = // How??
  // Output: Map( orgId as Long -> orgName as String )

}

object OrgRegistryConfig {
  case class Organisation() {
    var orgId: Long = _
    var orgName: String = _
  }
}

Upvotes: 1

Views: 1762

Answers (2)

Tim
Tim

Reputation: 27356

This is probably the most efficient solution:

def toMap: Map[Long, String] =
  organisations.map(o => o.orgId -> o.orgName)(collection.breakOut)

Using breakOut means that the Map will be created directly from the Array. If you use toMap then it will create an intermediate array which is then converted to a Map.

Upvotes: 2

Dima
Dima

Reputation: 40500

organisations.map { o => o.orgId -> o.orgName }.toMap

^^ that should do it.

On a related note, don't use var unless you know for sure the exact reason why you must be using it (95% of cases in scala you don't need it, and it's best to just pretend that keyword does not exist, until you have enough of a grasp of the language to distinguish those rare cases when you do), and definitely not in case classes.

Also, don't declare case class members outside of the constructor. And do not create case classes without parameters.

case class OrgRegistryConfig(organizations: Array[Organization]) {
  def toMap = organizations.map { o => o.orgId -> o.orgName }.toMap
}

Upvotes: 5

Related Questions