Skip to content

Instantly share code, notes, and snippets.

@timyates
Created November 9, 2012 15:47
Show Gist options
  • Save timyates/4046419 to your computer and use it in GitHub Desktop.
Save timyates/4046419 to your computer and use it in GitHub Desktop.
De-structuring a list of maps based on given keys
def data = [
[ user:'tim', time:1, age:33, weight:90, height:2.2 ],
[ user:'anne', time:2, height:1.8 ]
]
def destructure = { List<Map> listOfMaps, idFields=[], boolean allowNull=true ->
[ idFields ].flatten().with { flatFields ->
( listOfMaps*.keySet().flatten() as Set ).with { names ->
names = names - flatFields
listOfMaps.inject( [] ) { list, map ->
map.subMap( flatFields ).with { m ->
list.addAll( names.findResults { name ->
if( map[name] != null || allowNull ) {
[ *:m, (name): map[name] ]
}
} )
list
}
}
}
}
}
assert destructure( data ) == [
[user:'tim'],
[time:1],
[age:33],
[weight:90],
[height:2.2],
[user:'anne'],
[time:2],
[age:null],
[weight:null],
[height:1.8]
]
assert destructure( data, 'user' ) == [
[user:'tim', time:1],
[user:'tim', age:33],
[user:'tim', weight:90],
[user:'tim', height:2.2],
[user:'anne', time:2],
[user:'anne', age:null],
[user:'anne', weight:null],
[user:'anne', height:1.8]
]
assert destructure( data, [ 'user', 'time' ] ) == [
[user:'tim', time:1, age:33],
[user:'tim', time:1, weight:90],
[user:'tim', time:1, height:2.2],
[user:'anne', time:2, age:null],
[user:'anne', time:2, weight:null],
[user:'anne', time:2, height:1.8]
]
assert destructure( data, [ 'user', 'time' ], false ) == [
[user:'tim', time:1, age:33],
[user:'tim', time:1, weight:90],
[user:'tim', time:1, height:2.2],
[user:'anne', time:2, height:1.8]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment