user2585393
user2585393

Reputation: 27

Group By a particular column

New to scala, having tough time around maps and lists, its not the same as java say I have a scala function which gives me the records from a database which are in the following format with columns

id owner_id type_id name value

Let's name this as a

case class Row(id: UUID, ownerId: UUID, typeId: UUID, name: String, value: String)

Now I want to write a function which takes these rows as input and spits out a map in Scala which looks like the following, can someone please help me with a function

{
  "owner": "ownerId",
  "configurations": {
    "type1": {
      "name1": "value1",
      "name2": "value2"
    },
    "type2": {
      "name3": "value3",
      "name4": "value4"
    }
  }
}

Upvotes: 0

Views: 42

Answers (1)

ntn
ntn

Reputation: 1177

Assuming this result type

case class Data(owner: UUID, configurations: Map[UUID, Map[String, String]])

I haven't tested this, but this might work to get configurations field. Since there are multiple rows, I'm not sure how owner field can be populated with one value.

def convert(rows: Seq[Row]): Data =
  Data(owner = ???,
       configurations = rows.groupMapReduce(_.typeId)(r => Map(r.name -> r.value))(_ ++ _))

This uses the groupMapReduce function in Seq, which will first group all rows based on typeId. It'll then map each row r to a Map with one entry name to value. ++ will then combine all these small Maps.

Upvotes: 1

Related Questions