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 = _
  }
}

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thank you! I am using Spring Boot ConfigurationProperties, therefor I had to replicate some Java-behavior to make it work. stackoverflow.com/a/54982686/2291510
Yeah ... don't use that.
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 :)
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.

Comments

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.