Does Scala LinkedHashMap.toMap save the order?

As indicated in the title, does LinkedHashMap convert the order in which the elements are stored into a map?

I do not believe, but did not find any evidence.

Alternatively, is there any implementation of an immutable Map in Scala that preserves the order in which elements are inserted?

+4
source share
3 answers

The general Map interface does not guarantee such a guarantee. It also cannot be, as this would preclude HashMap as a possible implementation.

I believe that collection.immutable.ListMap maintains the insertion order, you can also use LinkedHashMap through the Map interface, which will then prevent access to any mutator methods. This is simple enough to do by explicitly specifying the type:

 val m: scala.collection.Map[Int,Int] = collection.mutable.LinkedHashMap(1->2, 2->3) 

or (using type):

 val m = collection.mutable.LinkedHashMap(1->2, 2->3) : Map[Int,Int] 
+9
source

No, LinkedHashMap.toMap does not preserve the insertion order.

The best way I know is to convert it to ListMap (immutable):

 def toMap[A, B](lhm: mutable.LinkedHashMap[A, B]): ListMap[A, B] = ListMap(lhm.toSeq: _*) 

Simply hiding mutation methods is not the same as converting to an immutable object.

+5
source

You can use TreeMap :

 TreeMap(Map(1 -> "one", 2 -> "two", 3 -> "three").toArray:_*).map(println) 
-4
source

All Articles