如何避免映射连接的奇怪顺序?(A ++ B ++ C ---> BAC)

3 scala map

连接三个地图a,b和c,我希望结果与其各自的原始地图的顺序相同.但是,如下所示,结果就像地图是b,a和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)
Run Code Online (Sandbox Code Playgroud)

对于四个地图,它显示b,d,a,c.对于两个b,a.无论原始序列如何,生成的地图始终处于相同的顺序.


测试答案:

  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)
Run Code Online (Sandbox Code Playgroud)

Tra*_*own 10

Scala Map(与Java一样)没有定义的迭代顺序.如果需要维护插入顺序,可以使用a ListMap(不可变)或a LinkedHashMap(不是):

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)
Run Code Online (Sandbox Code Playgroud)

但总的来说,如果你关心你的元素的顺序,你可能会更好地使用不同的数据结构.