2016-04-13 8 views
1

immutable.Mapに変換したい要素の順序を保存するIterable(k->v)があります。最良のターゲットMapタイプはListMapです。どのような方法をListMaptoMapを使用してIterableで入手できますか?具体的なマップの実装でIterable toMap

+0

[ 'Iterable.toMap']の戻り値の型(HTTP ://www.scala-lang.org/api/current/#scala.collection.Iterable)は 'immutable.Map'です。それはあいまいですか、またはライブラリの変更方法を尋ねていますか? –

答えて

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) 
関連する問題