1

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?

towel
  • 2,094
  • 1
  • 20
  • 30

1 Answers1

4

You could do it this way with inject and withDefault on an empty map:

def m = [a: [1, 2], b: [1, 3, 4]]

m.inject([:].withDefault {[]}) { map, value ->
    value.value.each { map[it] << value.key }
    map
}
tim_yates
  • 167,322
  • 27
  • 342
  • 338