开发者

Scala LinkedHashMap.toMap preserves order?

开发者 https://www.devze.com 2023-03-09 22:05 出处:网络
As the title states, does converting a LinkedHashMap to a Map preserve the order in which elements are stored?

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 M开发者_开发百科ap in Scala that preserves the order in which elements are inserted?


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]


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.


You can use TreeMap:

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

精彩评论

暂无评论...
验证码 换一张
取 消