Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala convert List of map to map

Tags:

scala

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

like image 923
Muhunthan Avatar asked Mar 09 '17 09:03

Muhunthan


People also ask

How to convert list to map in Scala?

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.

What is flatMap in Scala?

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.

How do you make a map in Scala?

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.

How do you create an empty list in Scala?

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.


2 Answers

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.

like image 160
Andrei T. Avatar answered Sep 26 '22 08:09

Andrei T.


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.

like image 40
Pavithran Ramachandran Avatar answered Sep 24 '22 08:09

Pavithran Ramachandran