Home > Enterprise >  How to transform a List[Map[String, String]] in Scala
How to transform a List[Map[String, String]] in Scala

Time:06-02

I have a Scala List of Map[String, String] like this:

val data: List[Map[String, String]] = List(Map("key" -> "123", "fname" -> "Alice", "lname" -> "Baker"), Map("key" -> "456", "fname" -> "Bob", "lname" -> "Lotts"))

I want to transform this to a List like this: List(Map(id -> 123, name -> Alice Baker), Map(id -> 456, name -> Bob Lotts)). Basically, I need to change the key to id and concatenate the fname and lname to name.

I tried the below code. It works, but I am sure there should be a better way of doing this. Can anyone please suggest?

val modData: List[Map[String, String]] = data.map(d => Map("id" -> d.getOrElse("key", ""), "name" -> s"${d.getOrElse("fname", "")} ${d.getOrElse("lname", "")}"))

CodePudding user response:

I would do it in steps, and use default for the map to make it more readable:

    val keys = Seq("key", "fname", "lname")
    list.iterator
      .map(_.withDefault(_ => ""))
      .map(keys.map)
      .collect { case Seq(id, fname, lname) => Map("id" -> id, "name" -> s"$fname $lname") }
      .toList

CodePudding user response:

All you need to do is get the value of each attribute and concatenate them together

val modData: List[Map[String, String]] = data.map(d => Map("id" -> d.apply("key"), "name" -> (d.apply("fname") " " d.apply("lname"))))
  • Related