【问题标题】:Scala best way of turning a Collection into a mutable Map-by-keyScala 将 Collection 转换为可变 Map-by-key 的最佳方法
【发布时间】:2015-03-10 21:47:37
【问题描述】:

Here 是从 colleciton 构建不可变 Map 的示例。除了可变的,如何做同样的事情? (没有将生成的不可变 Map 转换为可变 Map)

【问题讨论】:

  • 如果有人发表评论他们为什么不赞成,那就太好了。 :)

标签: scala dictionary collections immutability mutable


【解决方案1】:
scala> :paste
// Entering paste mode (ctrl-D to finish)

val l = List(1,2,3,4)
def f(i:Int ) = (i*10,i)
val m = scala.collection.mutable.Map(l map f : _*)

// Exiting paste mode, now interpreting.

l: List[Int] = List(1, 2, 3, 4)
f: (i: Int)(Int, Int)
m: scala.collection.mutable.Map[Int,Int] = Map(20 -> 2, 40 -> 4, 10 -> 1, 30 -> 3)

【讨论】:

    【解决方案2】:
    scala> val mutableMap = scala.collection.mutable.Map.empty[ String , String ]
    mutableMap: scala.collection.mutable.Map[String,String] = Map()
    
    scala> val myList = (1 to 10).toList
    myList: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    
    scala> myList.foreach( i => mutableMap += ( i.toString -> ( i * i ).toString ) )
    
    scala> mutableMap
    res6: scala.collection.mutable.Map[String,String] = Map(2 -> 4, 5 -> 25, 8 -> 64, 7 -> 49, 1 -> 1, 4 -> 16, 6 -> 36, 9 -> 81, 10 -> 100, 3 -> 9)
    
    // you can also do this by using _* annotation as follows
    
    // first create a immutable map
    scala> myList.map( i => ( i.toString -> ( i * i ).toString ) )
    res7: scala.collection.immutable.Map[String,String] = Map(2 -> 4, 5 -> 25, 8 -> 64, 7 -> 49, 1 -> 1, 4 -> 16, 6 -> 36, 9 -> 81, 10 -> 100, 3 -> 9)
    
    // then feed the elements of this map as *-parameter argument
    scala> scala.collection.mutable.Map( res7: _* )
    res7: scala.collection.mutable.Map[String,String] = Map(2 -> 4, 5 -> 25, 8 -> 64, 7 -> 49, 1 -> 1, 4 -> 16, 6 -> 36, 9 -> 81, 10 -> 100, 3 -> 9)
    

    【讨论】:

      猜你喜欢
      • 2010-10-15
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-27
      相关资源
      最近更新 更多