I have a simple question
I have List of Map like this
List(
Map("a" -> "a"),
Map("b" -> "b")
)
And I want the result like this
Map(
"a"->"a",
"b"->"b"
)
It can be overwrite if the key is duplication Any one please help me
To convert a list into a map in Scala, we use the toMap method. We must remember that a map contains a pair of values, i.e., key-value pair, whereas a list contains only single values. So we have two ways to do so: Using the zipWithIndex method to add indices as the keys to the list.
In Scala, flatMap() method is identical to the map() method, but the only difference is that in flatMap the inner grouping of an item is removed and a sequence is generated. It can be defined as a blend of map method and flatten method.
Map class explicitly. If you want to use both mutable and immutable Maps in the same, then you can continue to refer to the immutable Map as Map but you can refer to the mutable set as mutable. Map. While defining empty map, the type annotation is necessary as the system needs to assign a concrete type to variable.
If you want to use the add operation, you would have to declare an ArrayList. Vals in scala are essentially immutable, so you can't add to them. iirc val is more like final, you can add to them if you use the mutable Collections.
You can combine flatten
and toMap
:
val list = List(Map("k1" -> "v1", "k2" -> "v2"))
list.flatten.toMap // Map(k1 -> v1, k2 -> v2)
flatten
will convert the list of maps into a list of tuples and then toMap
will convert your list of tuples into a map.
You can try using reduce:
scala> val list = List(Map("k1" -> "v1", "k2" -> "v2"))
list: List[scala.collection.immutable.Map[String,String]] = List(Map(k1 -> v1, k2 -> v2))
scala> list.reduce(_ ++ _)
res0: scala.collection.immutable.Map[String,String] = Map(k1 -> v1, k2 -> v2)
scala> val list = List(Map("k1" -> "v1"), Map("k2" -> "v2"))
list: List[scala.collection.immutable.Map[String,String]] = List(Map(k1 -> v1), Map(k2 -> v2))
scala> list.reduce(_ ++ _)
res1: scala.collection.immutable.Map[String,String] = Map(k1 -> v1, k2 -> v2)
This way you needn't convert to any intermediate data type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With