'How to replace an Item in scala Map, keeping the order
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??
Solution 1:[1]
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.
Solution 2:[2]
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
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Guru Stron |
Solution 2 | Tim |