3

连接三个地图 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)

对于四个地图,它显示 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)
4

1 回答 1

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)

但总的来说,如果您关心元素的顺序,那么使用不同的数据结构可能会更好。

于 2013-02-06T01:35:42.453 回答