halfwarp
halfwarp

Reputation: 1790

Scala LinkedHashMap.toMap preserves order?

As the title states, does converting a LinkedHashMap to a Map preserve the order in which elements are stored?

I believe not, but couldn't find any evidence.

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

Upvotes: 6

Views: 6511

Answers (3)

Kevin Wright
Kevin Wright

Reputation: 49705

The generic Map interface makes no such guarantee of ordering. Nor can it, as this would then rule out HashMap as a possible implementation.

I believe collection.immutable.ListMap preserves insertion order, you could also use a LinkedHashMap via the Map interface, which would then prevent access to any mutator methods. This is easy 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 ascription):

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

Upvotes: 10

mauhiz
mauhiz

Reputation: 501

No, LinkedHashMap.toMap does not retain insertion order.

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

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

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

Upvotes: 9

Dmitry Stropalov
Dmitry Stropalov

Reputation: 790

You can use TreeMap:

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

Upvotes: -5

Related Questions