Groovy - Add Map Entry with Iterator
dictionary, groovy
Solution
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']`
Problem
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"] ``` ???