Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy - Add Map Entry with Iterator

Tags:

map

groovy

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"]

???

like image 535
user1785330 Avatar asked Oct 30 '12 12:10

user1785330


People also ask

How do I add a map to Groovy?

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.

Can we use iterator in map?

First of all, we cannot iterate a Map directly using iterators, because Map are not Collection.


1 Answers

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']

like image 91
tim_yates Avatar answered Oct 08 '22 00:10

tim_yates