Transpose a card collecting keys along the way

I am trying to transfer a card so that:

[x: y, w: y, a: b] 

becomes

 [y: [x, w], b: a] 

(all variables are strings) Doing something like

 ["x": "y", "w": "y", "a": "b"].collectEntries { [it.value, it.key] } 

gets me partially, but stomps on the first new value for "y". I get only: [y: w, b: a]

What is the best way to expand new values ​​into an array for their shared new key? Thanks for any help or suggestions.

+7
maps transpose groovy
source share
2 answers

Hope this helps:

 def map = ["x": "y", "w": "y", "a": "b"] map.groupBy{ it.value }.collectEntries{ k, v -> [k, v.keySet()] } 
+16
source share

I had a similar requirement, but individual keys are needed (type of rotation), so my solution is slightly different:

 def map = ["x": "y", "w": "y", "a": "b"] def newKeys = map.collect{ it.value }.flatten() as Set def transpose = newKeys.collectEntries{ [ (it): map.findAll{ k, v -> v.contains(it) }.collect{ it.key } ]} println transpose // [y:[x, w], b:[a]] 
+2
source share

All Articles