使用具体的地图实现可迭代toMap

Sta*_*tas 1 scala

有一个Iterable(k->v)我想转换成immutable.Map保存元素的顺序.最好的目标Map类型是ListMap.有没有什么办法让ListMap使用toMapIterable

And*_*wik 5

尝试:

scala> val iterable =  Iterable("a" -> 3,"t" -> 5,"y" -> 1, "c" -> 4)
iterable: Iterable[(String, Int)] = List((a,3), (t,5), (y,1), (c,4))

scala> import collection.immutable.ListMap
import collection.immutable.ListMap

scala> ListMap(iterable.toSeq:_*)
res3: scala.collection.immutable.ListMap[String,Int] = Map(a -> 3, t -> 5, y -> 1, c -> 4)
Run Code Online (Sandbox Code Playgroud)

更新 您必须通过隐式类/方法扩展API,例如:

scala> object IterableToListMapObject {
     | 
     |   import collection.immutable.ListMap
     | 
     |   implicit class IterableToListMap[T, U](iterable: Iterable[(T, U)]) {
     |     def toListMap: ListMap[T, U] = {
     |       ListMap(iterable.toSeq: _*)
     |     }
     |   }
     | 
     | }
defined object IterableToListMapObject

scala> import IterableToListMapObject._
import IterableToListMapObject._

scala> val iterable = Iterable("a" -> 3,"t" -> 5)
iterable: Iterable[(String, Int)] = List((a,3), (t,5))

scala> iterable.toListMap
res0: scala.collection.immutable.ListMap[String,Int] = Map(a -> 3, t -> 5)
Run Code Online (Sandbox Code Playgroud)