如何将 List(String,String) 转换为 ListMap[String,String]?
how to convert List(String,String) to ListMap[String,String]?
我有一个 List(String,String)
类型的列表,我想将其转换为地图。当我使用 toMap
方法时,我发现它不会保留列表中的数据顺序。但是,我的目标是通过保持数据顺序与列表相同来将列表转换为地图。我了解到 ListMap
保留了插入顺序(但它是不可变的)所以我可以使用带有 map 函数的 LinkedHashMap 将数据按顺序插入 LinkedHashMap
但这意味着我需要遍历所有元素是痛。谁能建议我一个更好的方法?
谢谢
应该这样做:
val listMap = ListMap(list : _*)
在 Scala 2.13 或更高版本中:
scala> import scala.collection.immutable.ListMap
import scala.collection.immutable.ListMap
scala> val list = List((1,2), (3,4), (5,6), (7,8), (9,0))
list: List[(Int, Int)] = List((1,2), (3,4), (5,6), (7,8), (9,0))
scala> list.to(ListMap)
res3: scala.collection.immutable.ListMap[Int,Int] = ListMap(1 -> 2, 3 -> 4, 5 -> 6, 7 -> 8, 9 -> 0)
不要使用 ListMap。他们表现极差。由于它们被构造为列表,因此它们具有线性查找性能 (https://docs.scala-lang.org/overviews/collections/performance-characteristics.html)
我建议实例化一个可变的 LinkedHashmap,然后将其分配给定义为 collections.Map 的 val。 collection.Map 接口不公开可变方法,因此映射对于访问它的任何实体都是不可变的。
我有一个 List(String,String)
类型的列表,我想将其转换为地图。当我使用 toMap
方法时,我发现它不会保留列表中的数据顺序。但是,我的目标是通过保持数据顺序与列表相同来将列表转换为地图。我了解到 ListMap
保留了插入顺序(但它是不可变的)所以我可以使用带有 map 函数的 LinkedHashMap 将数据按顺序插入 LinkedHashMap
但这意味着我需要遍历所有元素是痛。谁能建议我一个更好的方法?
谢谢
应该这样做:
val listMap = ListMap(list : _*)
在 Scala 2.13 或更高版本中:
scala> import scala.collection.immutable.ListMap
import scala.collection.immutable.ListMap
scala> val list = List((1,2), (3,4), (5,6), (7,8), (9,0))
list: List[(Int, Int)] = List((1,2), (3,4), (5,6), (7,8), (9,0))
scala> list.to(ListMap)
res3: scala.collection.immutable.ListMap[Int,Int] = ListMap(1 -> 2, 3 -> 4, 5 -> 6, 7 -> 8, 9 -> 0)
不要使用 ListMap。他们表现极差。由于它们被构造为列表,因此它们具有线性查找性能 (https://docs.scala-lang.org/overviews/collections/performance-characteristics.html)
我建议实例化一个可变的 LinkedHashmap,然后将其分配给定义为 collections.Map 的 val。 collection.Map 接口不公开可变方法,因此映射对于访问它的任何实体都是不可变的。