1

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 = _
  }
}
Mr.Turtle
  • 2,950
  • 6
  • 28
  • 46

2 Answers2

5

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
}
Dima
  • 39,570
  • 6
  • 44
  • 70
  • Hi, thank you! I am using Spring Boot ConfigurationProperties, therefor I had to replicate some Java-behavior to make it work. https://stackoverflow.com/a/54982686/2291510 – Mr.Turtle Mar 04 '19 at 13:03
  • 2
    Yeah ... don't use that. – Dima Mar 04 '19 at 13:06
  • I can't do it differently as I know. This is a large application written in Scala & Spring Boot. The list needs to be updated in a running cloud solution without re-deploying the application. I can't put this in a database. Having it in a configmap does the work :) – Mr.Turtle Mar 04 '19 at 15:00
2

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.

Tim
  • 26,753
  • 2
  • 16
  • 29