0

I have string of columns and they are grouped by they purpose etc address cols and personal info cols. val columns="address:addressLine,address:city,address:state,address:zipCode,person:firstName,person:lastName,person:middleName"

I wanted them to be arranged like that:

lastName->person,zipCode->address

So every pair like lastName->person would be a Map. I wanted these Maps to be placed inside another Map, like that:

columnSchema -> {
lastName->person,
zipCode->address
}

So it would be Map[String,Map[String,String]]

I started by doing it like that:

columns.split(",").map(_.split(":")).map(x=>Map(x(1)->x(0)))

What I got is:

Array[scala.collection.immutable.Map[String,String]] = Array(Map(addressLine -> address), Map(city -> address), Map(state -> address), Map(zipCode -> address), Map(firstName -> person), Map(lastName -> person), Map(middleName -> person))

So I got an Array[Map[String,String]]. How could I make it a Map[String,Map[String,String]]? I tried to do it like:

Map("columnSchema" -> columns.split(",").map(_.split(":")).map(x=>Map(x(1)->x(0))))

However it still returns an array of Maps:

scala.collection.immutable.Map[String,Array[scala.collection.immutable.Map[String,String]]]

How to get rid of an Array? Thanks!

2 Answers 2

2

Similar to what you have except add in toMap to convert the Array of tuples to a Map

Map("columnSchema" -> columns.split(",").map(_.split(":")).map(as => as(1) -> as(0)).toMap)

Returns:

Map[String, Map[String, String]] = 
Map(columnSchema -> 
  HashMap(city -> address,
          middleName -> person,
          state -> address,
          addressLine -> address,
          zipCode -> address,
          lastName -> person,
          firstName -> person)
)
Sign up to request clarification or add additional context in comments.

Comments

2

Another option could be splitting on : or , using a character class [,:] and then group the result in collections of 2 and map using a partial function.

val res: Map[String, Map[String, String]] = Map(
  "columnSchema" -> 
    columns.split("[,:]").grouped(2)
    .map { case Array(k, v) => v -> k }.toMap
)

Output

Map(
columnSchema -> Map(
    city -> address,
    middleName -> person,
    state -> address,
    addressLine -> address,
    zipCode -> address,
    lastName -> person,
    firstName -> person
    )
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.