How to avoid the strange order in which the cards are combined? (A ++ B ++ C ---> BAC)

By combining three cards a, b and c, I expect the result to be in the same order as the corresponding original cards. But as shown below, the result is similar to maps b, a and c:

  Welcome to Scala version 2.10.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_26).
  Type in expressions to have them evaluated.
     Type :help for more information.

  scala> import collection.mutable
  import collection.mutable

  scala> val a = mutable.Map(1->2)
  a: scala.collection.mutable.Map[Int,Int] = Map(1 -> 2)

  scala> val b = mutable.Map(2->2)
  b: scala.collection.mutable.Map[Int,Int] = Map(2 -> 2)

  scala> val c = mutable.Map(3->2)
  c: scala.collection.mutable.Map[Int,Int] = Map(3 -> 2)

  scala> a ++ b ++ c
  res0: scala.collection.mutable.Map[Int,Int] = Map(2 -> 2, 1 -> 2, 3 -> 2)

      

For four cards, he shows b, d, a, c. For two b, a. The resulting map is always in the same order, regardless of the original sequence.


Checking the answer:

  Welcome to Scala version 2.10.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_26).
  Type in expressions to have them evaluated.
  Type :help for more information.

  scala> import collection.mutable.LinkedHashMap
  import collection.mutable.LinkedHashMap

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

  scala> val b = LinkedHashMap(2 -> 2)
  b: scala.collection.mutable.LinkedHashMap[Int,Int] = Map(2 -> 2)

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

  scala> a ++ b ++ c
  res0: scala.collection.mutable.Map[Int,Int] = Map(1 -> 2, 2 -> 2, 3 -> 2)

      

+3


source to share


1 answer


Scala Map

(like Java) has no specific iteration order. If you need to maintain the order of insertion, you can use ListMap

(which is immutable) or LinkedHashMap

(it is not):

scala> import collection.mutable.LinkedHashMap
import collection.mutable.LinkedHashMap

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

scala> a += (2 -> 2)
res0: a.type = Map(1 -> 2, 2 -> 2)

scala> a += (3 -> 2)
res1: a.type = Map(1 -> 2, 2 -> 2, 3 -> 2)

scala> a
res2: scala.collection.mutable.LinkedHashMap[Int,Int] = Map(1 -> 2, 2 -> 2, 3 -> 2)

      



But in general, if you care about the order of your elements, you are probably better off working with a different data structure.

+10


source







All Articles