techie
techie

Reputation: 363

Convert dataframe to scala map

I have a dataframe like,

df.show
+----+-------+
| age|   name|
+----+-------+
|  20|Michael|
|  30|   Andy|
|  19| Justin|
+----+-------+

I need to put it in a scala Map like (Michael->20,Andy->30,Justin->19)

How can I achieve this?

Upvotes: 0

Views: 9637

Answers (1)

user9200942
user9200942

Reputation: 126

Plain and simple - convert to static types and collect:

df.select($"name", $"age".cast("int")).as[(String, Int)].collect.toMap

Though in practice there you won't find much use for that I guess, given it stores data in the driver memory.

Upvotes: 11

Related Questions