Muhunthan
Muhunthan

Reputation: 413

scala convert List of map to map

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

Upvotes: 10

Views: 16584

Answers (2)

Pavithran Ramachandran
Pavithran Ramachandran

Reputation: 993

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.

Upvotes: 7

Andrei T.
Andrei T.

Reputation: 2480

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.

Upvotes: 16

Related Questions