flatMapValues in Scala
flatMapValues is a powerful function to assign one key to multiple values in a row. Let’s look at an example:
For example, I have the data in the structure shown below:
We know that Marvel is the production company of all the movies in 1st row and DC is the production company of all the movies in 2nd row.
Now, if I have to link Marvel to each movie and similarly DC to each movie in 2nd row, I would use flatMapValues function. Before we look at the example, a couple of reminders:1) The delimiter between key and values is (,) different from the delimiter among values (space). So, this approach works when the delimiters are different. 2) The function takes input as tuples/key-value pairs.
As shown above, map function is used to convert the line into a key value pair tuple. This key value pair is now passed to flatMapvalues to get the final output shown below:
(Please note that the screenshot with only partial results are shown above as it gets lengthy)