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?
util. Map. of() , it does not preserve ordering.
If your comparator is on the insertion order, the tree will preserve the insertion order.
By default, Scala uses the immutable Map. If you want to use the mutable Map, you'll have to import scala.
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.
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 ListMap
s.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With