Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala LinkedHashMap.toMap preserves order?

Tags:

scala

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?

like image 401
halfwarp Avatar asked Jun 01 '11 09:06

halfwarp


2 Answers

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]
like image 61
Kevin Wright Avatar answered Nov 12 '22 23:11

Kevin Wright


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.

like image 39
mauhiz Avatar answered Nov 12 '22 22:11

mauhiz