【问题标题】:Iterable toMap with concrete map implementation具有具体地图实现的可迭代 toMap
【发布时间】:2016-04-13 07:18:03
【问题描述】:

有一个 Iterable(k->v) 我想将其转换为 immutable.Map 以保存元素的顺序。最佳目标Map 类型是ListMap。有什么方法可以在Iterable 上使用toMap 获得ListMap

【问题讨论】:

  • Iterable.toMap的返回类型为immutable.Map。这是模棱两可的,还是您在问如何修改库?

标签: scala


【解决方案1】:

试试:

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)

【讨论】:

  • @Steven Yang 请查看AnyVal。这种情况不适合它。
  • 怎么不是?这个案例看起来与文档中提到的案例完全一样。参见:RichInt
猜你喜欢
  • 2018-03-31
  • 1970-01-01
  • 2016-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多