Home > Mobile >  How to replace an Item in scala Map, keeping the order
How to replace an Item in scala Map, keeping the order

Time:05-12

I have a Map like this .

  val m1 = Map(1 -> "hello", 2 -> "hi", 3 -> "Good", 4 -> "bad")
  val m2 = Map(1 -> "Great", 3 -> "Guy")

Now I need to derive another Map from m1 and m2, and I need to replace elements of m1 by those m2 with order preserved.

m3 should like

   Map(1 -> "Great", 2 -> "hi",  3 -> "Guy", 4 -> "bad")

Is there a way to do it in functional programming??

CodePudding user response:

val m3 = m1    m2

However order is not preserved because Map is not ordered in the first place. If you want an ordered map use ListMap.

CodePudding user response:

Map does not preserve ordering. If you want to preserve insertion order use ListMap:

List map iterators and traversal methods visit key-value pairs in the order they were first inserted.

val m1 = ListMap(1 -> "hello", 2 -> "hi", 3 -> "Good", 4 -> "bad")
val m2 = Map(1 -> "Great", 3 -> "Guy")
val m3 = m1    m2

or SortedMap if you want ordering by the key:

An immutable map whose key-value pairs are sorted according to an scala.math.Ordering on the keys.

  • Related