gpt4 book ai didi

scala - 保留插入顺序的不可变 Scala Map 实现

转载 作者:行者123 更新时间:2023-12-03 06:07:44 26 4
gpt4 key购买 nike

LinkedHashMap用于保留映射中的插入顺序,但这仅适用于可变映射。哪个是不可变的 Map保留插入顺序的实现?

最佳答案

ListMap使用基于列表的数据结构实现不可变映射,从而保留插入顺序。

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)

以下扩展方法 - Seq#toListMap 在使用 ListMap 时非常有用。

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)

关于scala - 保留插入顺序的不可变 Scala Map 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9313866/

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