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]

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
Andy
  • 10,553
  • 21
  • 75
  • 125
  • (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.) –  Apr 11 '12 at 20:34
  • I apologize. I will add it now. – Andy Apr 11 '12 at 20:35
  • 1
    Note that TreeMap does not guarantee *insertion order* - it guarantees *ordered order* as it is effectively always sorted. –  Apr 11 '12 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. – Andy Apr 11 '12 at 20:42

1 Answers1

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.

dhg
  • 52,383
  • 8
  • 123
  • 144
  • 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 Apr 11 '12 at 20:34
  • @Andy, Yeah, if you have control over which implementation, when go ahead and use the ordered one. – dhg Apr 11 '12 at 20:36
  • 1
    Thank you very much. I did not know Scala had that, and the API is really hard to read. Much appreciated. – Andy Apr 11 '12 at 20:37
  • 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. – Andy Apr 11 '12 at 20:40
  • @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. –  Apr 11 '12 at 20:43
  • @pst - Ack, you're right. I was thinking of `ListMap`. Deleted previous comment to avoid confusion. – Rex Kerr Apr 11 '12 at 20:44