I'm trying to come up with a way to make keys out of a list of values.
For instance: I have this map [ a: [1, 2], b: [1, 3, 4] ]
I'd like to transform it into [ 1: [a, b], 2: [a], 3: [b], 4: [b] ]
Basically I ask for the groovy version of How to transform key/value in Map .
So far my solution is a bit excessive, because I collect all the values and create new value-key pairs:
def m = [ a: [1, 2], b: [1, 3, 4] ]
def transformed = m.collectMany { k, v -> v }.collectEntries { v -> [ v, [] ] }
m.collectMany { k, v -> v.collect { vi -> [ vi, k ] } }.each { v, k ->
transformed[v] += k
}
transformed
Is there a better way to achieve this transformation?