transpose a map collecting keys along the way

两盒软妹~` 提交于 2021-02-04 15:08:44

问题


I'm trying to transpose a map 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 part way, but stomps on the first new value for "y". I only get: [y:w, b:a]

What is the best way to slurp up the new values into an array for their common new key? Thanks for any help or suggestions.


回答1:


I hope this helps :

def map = ["x": "y", "w": "y", "a": "b"]

map.groupBy{ it.value }.collectEntries{ k, v -> [k, v.keySet()] }



回答2:


I had a similar requirement, but needed individual keys (kind of a pivot), so my solution is a little 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]]


来源:https://stackoverflow.com/questions/18022537/transpose-a-map-collecting-keys-along-the-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!