0

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]?

Klaus Schulz
  • 527
  • 1
  • 5
  • 20

1 Answers1

3

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
dth
  • 2,287
  • 10
  • 17
  • You should be recommending JavaConverters, not JavaConversions. http://stackoverflow.com/questions/8301947/what-is-the-difference-between-javaconverters-and-javaconversions-in-scala – Seth Tisue Feb 09 '16 at 03:19