5

I have been looking around, but most of them point to a java TreeMap. The only issue with that is I do not want to convert any Scala into java and back. If there really is no way, then I am ok with that, but I would like to hear it from some professionals just to be 100% sure and to have this question on here for others in the future to stumble upon when they have a similar issue. Thanks in advance.

EDIT:

Type: scala.collection.mutable.HashMap[String, String]

4
  • (While it doesn't matter in this case, it's important to be precise about types; e.g. include the FQN at some point. There is HashMap from Java, mutable HashMap and immutable HashMap, for instance.) Commented Apr 11, 2012 at 20:34
  • I apologize. I will add it now. Commented Apr 11, 2012 at 20:35
  • 1
    Note that TreeMap does not guarantee insertion order - it guarantees ordered order as it is effectively always sorted. Commented Apr 11, 2012 at 20:39
  • Oh really. Hmm, I guess there are tradeoffs in trying to get a key value pair in insertion order. Thanks for that. Commented Apr 11, 2012 at 20:42

1 Answer 1

11

In general, a Scala HashMap does not guarantee the original order.

However, there is the LinkedHashMap, which states: "The iterator and all traversal methods of this class visit elements in the order they were inserted."

What is the exact type you are dealing with? If you can decide which implementation to use, then you can choose one that maintains order. If you are just given something of type HashMap, then you're out of luck.

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

6 Comments

Oh really. I am dealing with a scala.collection.mutable.HashMap But if Scala has a LinkedHashMap I can use that instead. I just need a way to maintain order.
@Andy, Yeah, if you have control over which implementation, when go ahead and use the ordered one.
Thank you very much. I did not know Scala had that, and the API is really hard to read. Much appreciated.
Ahh, yes. I am aware @RexKerr - performance isn't the focal point of the homework, but I will keep this in mind. Thanks for the advice.
@RexKerr That is not true at all. It is a Linked Hash Map, not a Linked Scan Map ;-) It just maintains a double-linked list (of which nodes are referenced from the buckets that are still hashed to like the normal HashMap). Since each bucket entry references a double-linked node it can be deleted in O(1) and still has the expected O(1) access.
|

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.