score:4

Accepted answer

it can be thought of as:

first we map:

val a = map("a" -> list(1 -> 11,1 -> 111), "b" -> list(2 -> 22,2 -> 222)).map(e => e._2) 
// list(list((1, 11), (1, 111)), list((2, 22), (2, 222)))

then we flatten:

val b = a.flatten
// list((1, 11), (1, 111), (2, 22), (2, 222))

then we convert back to a map:

b.tomap
// map(1 -> 111, 2 -> 222)

since a map cannot have 2 values for 1 key, the value is overwritten.


really whats going on is that the flatmap is being converted into a loop like so:

for (x <- m0) b ++= f(x)

where:

  • m0 is our original map

  • b is a collection builder that has to build a map, aka, mapbuilder

  • f is our function being passed into the flatmap (it returns a list[(int, int)])

  • x is an element in our original map

the ++= function takes the list we got from calling f(x), and calls += on every element, to add it to our map. for a map, += just calls the original + operator for a map, which updates the value if the key already exists.

finally we call result on our builder which just returns us our map.


Related Query