Blankman Blankman - 4 years ago 131
Scala Question

How would I convert to linkedhashmap to a java type?

I am using a java API that requires a linkedhashmap

LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>();

Should I just use the scala version and then convert it somehow?

I created my mutable map:

val l = mutable.LinkedHashMapString,String

And I am trying to convert it using:

import scala.collection.JavaConverters._


I am getting the error:

[error] found : java.util.Map[String,String]
[error] required: java.util.LinkedHashMap[String,String]

Answer Source

Most Java collections have a constructor that lets you create them from another collection.

new LinkedHashMap[String, String](l.asJava)

You could also fold your scala collection into a java one explicitly

l.foldLeft(new java.util.LinkedHashMap[String, String]){(acc, x) => acc.put(x._1, x._2); acc}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download