1

I want to convert below dataframe into Map[String,List[String]]. I have changed initial dataframe to get Name columns in List format(using collect_list) but I am not able to convert it into Map[String,List[String]].

DataFrame

+---------+-------+
|City     |  Name |
+---------+-------+
|Mumbai   |[A,B]  |
|Pune     |[C,D]  |
|Delhi    |[A,D]  |
+---------+-------+

Expected Output:

Map(Mumbai -> List(A,B), Pune -> List(C,D), Delhi-> List(A,D))

1 Answer 1

1

You can convert to rdd and collect as Map as below

val df = Seq(
  ("Mumbai", List("A", "B")),
  ("Pune", List("C", "D")),
  ("Delhi", List("A", "D"))
).toDF("city", "name")

val map: collection.Map[String, List[String]] =  df.rdd
  .map(row => (row.getAs[String]("city"), row.getAs[List[String]]("name")))
  .collectAsMap()

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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