gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:33:55 25 4
gpt4 key购买 nike

连接三个 map a、b 和 c,我希望结果与其各自的原始 map 的顺序相同。但是,如下图,结果就像 map 是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)

对于四张 map ,它显示 b、d、a、c。对于两个 b,a。无论原始顺序如何,生成的 map 始终是相同的顺序。


测试答案:

  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)

最佳答案

Scala 的 Map(与 Java 类似)没有定义的迭代顺序。如果您需要维护广告订单,可以使用 ListMap (不可变)或 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)

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

关于scala - 如何避免 map 连接的奇怪顺序? (A++B++C ---> BAC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14720018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com