Reputation: 4827
I am a Java programmer trying to write some Groovy code.
I want to iterate through the map called loginAttributevalues, and for each key (e.g. username) find the cross-reference attribute value and print this:
john : display_name
However, I am having trouble getting my Java brain around the Groovy syntax. Can someone point me in the right direction? Thanks.
loginAttributeValues = [username: 'john', email: '[email protected]']
def mapXref = [username: 'display_name',
firstname: 'first_name',
lastname: 'last_name',
email: 'email'}
for (String x : loginAttributeValues) {
if (mapXref[x])
println(mapXref.get(x))
}
Upvotes: 0
Views: 168
Reputation: 50245
loginAttributeValues = [username: 'john', email: '[email protected]']
def mapXref = [username: 'display_name',
firstname: 'first_name',
lastname: 'last_name',
email: 'email']
def newMap = [:]
loginAttributeValues.each {k, v ->
newMap << (k in mapXref.keySet() ? [(v): mapXref[k]] : [:])
}
assert newMap.'john' == 'display_name'
assert newMap.'[email protected]' == 'email'
I hope you need a map like
[john:display_name, [email protected]:email]
but why do you need a value john
as a key
and display_name
as value
. should not it be otherwise. In that case, you would need
newMap << (k in mapXref.keySet() ? [mapXref[k] : v] : [:])
which would assert as
assert newMap.display_name == 'john'
assert newMap.email == '[email protected]'
Note:-
If it is guaranteed that loginAttributeValues
will have keys
subset of the keys
in mapXref
, then the logic can be optimized as below
def newMap = loginAttributeValues.collectEntries{k, v ->
[v, mapXref[k]]
}
Upvotes: 0
Reputation: 28737
This should work for you:
loginAttributeValues.each {
if (mapXref[it])
println(mapXref.get(it))
}
The Java for : each syntax is not valid in groovy. You are best of using an each
closure.
Or, if you really want to keep the for loop syntax, then substitute in
for :
.
Upvotes: 1