Klaus Schulz February 2016

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

Answers


dth February 2016

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

Post Status

Asked in February 2016
Viewed 3,228 times
Voted 4
Answered 1 times

Search




Leave an answer