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