Klaus Schulz
Klaus Schulz

Reputation: 547

Convert java.util.Map to Scala List[NewObject]

I have a java.util.Map[String, MyObject] and want to create a Scala List[MyNewObject] consisting of alle entries of the map with some special values.

I found a way but, well, this is really ugly:

val result = ListBuffer[MyNewObject]()
myJavaUtilMap.forEach
  (
   (es: Entry[String, MyObject]) => 
      { result += MyNewObject(es.getKey(), ey.getValue().getMyParameter); println("Aa")}
  )

How can I get rid of the println("Aa")? Just deleting does not help because foreach needs a Consumer but the += operation yields a list....

Is there a more elegant way to convert the java.util.Map to a List[MyNewObject]?

Upvotes: 0

Views: 56

Answers (1)

dth
dth

Reputation: 2337

Scala has conversions that give you all the nice methods of the Scala collection API on Java collections:

import collection.JavaConversions._
val result = myJavaUtilMap.map{
  case (k,v) => MyNewObject(k, v.getMyParameter)
}.toList

By the way: to define a function which returns Unit, you can explicitly specify the return type:

val f = (x: Int)  => x: Unit

Upvotes: 3

Related Questions