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

时间:2016-04-13 07:18:04

标签: scala

我想将Iterable(k->v)转换为immutable.Map,以保存元素的排序。最佳目标Map类型为ListMap。有没有办法在ListMap上使用toMap获取Iterable

1 个答案:

答案 0 :(得分: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)

<强>更新 您必须通过隐式类/方法扩展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)