user3370773
user3370773

Reputation: 455

How to convert a SortedMap to mutable Map

I have a datatype of the following format:

Iterable[scala.collection.SortedMap[String,Double]]

and I need the following datatype:

scala.collection.mutable.Map[String, Double]

Thanks

Upvotes: 1

Views: 592

Answers (3)

4e6
4e6

Reputation: 10776

It looks more like a hack, but anyway

scala> val a = collection.SortedMap("a" -> 1.1, "b" -> 2.2)
a: scala.collection.SortedMap[String,Double] = Map(a -> 1.1, b -> 2.2)

scala> type MMap = collection.mutable.Map[String, Double]
defined type alias MMap

scala> a.to[({type l[A] = collection.mutable.Map[String, Double]})#l]
res1: scala.collection.mutable.Map[String,Double] = Map(b -> 2.2, a -> 1.1)

Convert Map to mutable.Map

scala> a.to[({type l[a] = MMap})#l]
res0: scala.collection.mutable.Map[String,Double] = Map(b -> 2.2, a -> 1.1)

Convert Iterable[Map] to mutable.Map

scala> val as = Iterable.fill(1)(a)
as: Iterable[scala.collection.SortedMap[String,Double]] = List(Map(a -> 1.1, b -> 2.2))

scala> val ms: MMap = as.flatMap(_.to[({type l[a] = MMap})#l])(collection.breakOut)
ms: MMap = Map(b -> 2.2, a -> 1.1)

Also note that in this case, intersecting keys will be replaced by later one. See this one on how to merge maps with the same keys.

Upvotes: 0

ale64bit
ale64bit

Reputation: 6242

Assuming that what you want is to transform scala.collection.SortedMap[String,Double] into a scala.collection.mutable.Map[String, Double], you can do something like:

val m1 = SortedMap("key1" -> 1.0, "key2" -> 2.0) // immutable
val m2 = scala.collection.mutable.Map[String, Double]() ++= m1 // mutable

But if you REALLY want to transform Iterable[scala.collection.SortedMap[String,Double]] into scala.collection.mutable.Map[String, Double], then it is a bit unclear what do you expect as result exactly.

Hope it helped!

EDIT: then it means you really want to transform the Iterable into a single mutable map. Well, you can do this, although it looks as a terribly bizarre conversion. It would be nice to know why you want to convert that:

val m1 = SortedMap("key1" -> 1.0, "key2" -> 2.0) // immutable
val m2 = SortedMap("key3" -> 3.0, "key4" -> 4.0) // immutable
val it = Iterable(m1, m2)

val z = scala.collection.mutable.Map[String, Double]() ++= it.foldLeft[List[(String, Double)]](Nil)((x,m) => m.toList ::: x)

Upvotes: 2

elm
elm

Reputation: 20415

Convert the iterator first to a sequence, which can then be converted to a mutable Map. To illustrate this, let for instance

val a: scala.collection.SortedMap[String,Double] = SortedMap("a" -> 1.1, "b" -> 2.2)

Then

val m = scala.collection.mutable.Map( a.iterator.toSeq: _*)
m: scala.collection.mutable.Map[String,Double] = Map(b -> 2.2, a -> 1.1)

Note the ordering is lost in the resulting Map.

Upvotes: 2

Related Questions