Please explain, why this isn't working (Groovy 2.0.5 on JDK7). I just want to add some map entries from a list.
def map = new HashMap<String,String>()
map << ["key":"value"]
def list = ["a","b","c"]
list.each {
map << [it:"value"]
}
println map
println map.a
println map.containsKey("a")
/*
[key:value, a:value, b:value, c:value]
null <- ?
false <- ?
*/
It is also not working with:
map << ["$it":"value"]
But it is working with:
map << [(""+it):"value"]
???
Add Item to a Map The first way is using the square brackets for the key. This way useful if you have a dynamic key name for example the key name join with index. The second way is using a key separate with map name by a dot ".". Or this example also working in Groovy.
First of all, we cannot iterate a Map directly using iterators, because Map are not Collection.
This
map << [it:"value"]
Just uses a key called it
. If you wrap it in parentheses:
map << [(it):"value"]
It works as you wanted...
If you do:
map << ["$it":"value"]
Then, you can see that you have a GStringImpl
: as a key rather than a java.lang.String
println map.keySet()*.getClass().name
// prints [GStringImpl, GStringImpl, String, GStringImpl ]
(package names omitted for brevity)
Then, you try and look up a GString key with a String, and this fails (see the 'GStrings aren't Strings' section on this page)
This works:
map << [(""+it):"value"]
As it just creates a String (by appending it
to the empty String)
Anyway...long story short, use [(it):'value']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With