3

I'm new to Scala. I've been trying to convert a java LinkedHashMap to an equivalent collection(LinkedHashMap?) in Scala in order to preserve the insertion order.

Tried following things as suggested in other threads, but nothing seems to work!

scalaAsMap() - is messing up the order

TreeMap() - sort on keys, values, etc. is not something I'm looking for

Explicit conversion is not working.

val f = new java.util.LinkedHashMap[String, java.util.Map[String, String]]

var g: scala.collection.mutable.LinkedHashMap[String, java.util.Map[String, String]] = f
1
  • 1
    Use JavaConverters. See this doc Commented Oct 12, 2016 at 20:41

1 Answer 1

2

Hmm, how about:

val javaMap = new java.util.LinkedHashMap[String, String]()
val scalaMap = javaMap.asScala

The type of scalaMap is Map[String, String] but under the hood it behaves just like LinkedHashMap.

Sign up to request clarification or add additional context in comments.

2 Comments

javaMap.asScala is preserving the order of java map.
However this converts Map into a regular map. See the following error: type mismatch; found : scala.collection.Map[String,scala.collection.mutable.Map[String,String]] required: scala.collection.mutable.Map[String,scala.collection.mutable.Map[String,String]]

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.