-2

i need to get the keys from map in the order when they are added. but seems the map.keys return a array with re-ordered keys.

how to keep the order of the key/values as they added when retrieve them ?

Thanks

Hongwei Liu
  • 129
  • 1
  • 4
  • Have a look at [this question](http://stackoverflow.com/questions/9313866/immutable-scala-map-implementation-that-preserves-insertion-order) – mziccard Jun 26 '15 at 23:58
  • possible duplicate of [Scala Map implementation keeping entries in insertion order?](http://stackoverflow.com/questions/3835743/scala-map-implementation-keeping-entries-in-insertion-order) – The Archetypal Paul Jun 27 '15 at 07:55

1 Answers1

3

Maps implemented using trees don't store their keys in the order that they are inserted. That information is lost when it's inserted by value (based on its Comparable), and further "randomized" when the tree is balanced.

As @mziccard pointed out, linear structures (such as a LinkedHashMap) can preserve insertion order, so that's the way to go if you need such a capability.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • 1
    In Scala you have both a mutable map (LinkedHashMap) and an immutable one (LinkedMap) that allow you to preserve insertion order. Also Java has its LinkedHashMap preserving insertion order and capable also to track access order if required. – mziccard Jun 27 '15 at 00:12
  • My bad. I was thinking specifically of BST implementations. I'll correct that and reference you. – Carcigenicate Jun 27 '15 at 00:13