Search code examples
scaladataframehashmap

Converting a dataframe into a hashmap where Key is int and Value is a list in Scala


I have a dataframe which looks like this:

key words
1 ['a','test']
2 ['hi', 'there]

And I would like to create the following hashmap:

Map(1 -> ['a', 'test'], 2 -> ['hi', 'there'])

But I cannot figure out how to do this, can anyone help me?

Thanks!


Solution

  • There must be dozens of ways of doing this. One would be:

    df.collect().map { case row => (row.getAs[Int](0) -> row.getAs[mutable.WrappedArray[String]](1))}.toMap