Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable Scala Map implementation that preserves insertion order [duplicate]

LinkedHashMap is used to preserve insertion order in the map, but this only works for mutable maps. Which is the immutable Map implementation that preserves insertion order?

like image 383
Matroska Avatar asked Feb 16 '12 15:02

Matroska


People also ask

Does immutable map preserve order?

util. Map. of() , it does not preserve ordering.

Does Scala map maintain insertion order?

If your comparator is on the insertion order, the tree will preserve the insertion order.

Are maps immutable in Scala?

By default, Scala uses the immutable Map. If you want to use the mutable Map, you'll have to import scala.

Is Scala map ordered?

Solution. Scala has a wealth of map types to choose from, and you can even use Java map classes. If you're looking for a basic map class, where sorting or insertion order doesn't matter, you can either choose the default, immutable Map , or import the mutable Map , as shown in the previous recipe.


1 Answers

ListMap implements an immutable map using a list-based data structure, and thus preserves insertion order.

scala> import collection.immutable.ListMap import collection.immutable.ListMap  scala> ListMap(1 -> 2) + (3 -> 4) res31: scala.collection.immutable.ListMap[Int,Int] = Map(1 -> 2, 3 -> 4)  scala> res31 + (6 -> 9) res32: scala.collection.immutable.ListMap[Int,Int] = Map(1 -> 2, 3 -> 4, 6 -> 9) 

The following extension method - Seq#toListMap can be quite useful when working with ListMaps.

scala> import scalaz._, Scalaz._, Liskov._ import scalaz._ import Scalaz._ import Liskov._  scala> :paste // Entering paste mode (ctrl-D to finish)  implicit def seqW[A](xs: Seq[A]) = new SeqW(xs) class SeqW[A](xs: Seq[A]) {   def toListMap[B, C](implicit ev: A <~< (B, C)): ListMap[B, C] = {     ListMap(co[Seq, A, (B, C)](ev)(xs) : _*)     } }   // Exiting paste mode, now interpreting.  seqW: [A](xs: Seq[A])SeqW[A] defined class SeqW  scala> Seq((2, 4), (11, 89)).toListMap res33: scala.collection.immutable.ListMap[Int,Int] = Map(2 -> 4, 11 -> 89) 
like image 93
missingfaktor Avatar answered Sep 17 '22 04:09

missingfaktor