Anthony
Anthony

Reputation: 35938

How to look for a key in a Groovy Map that is of type GStringImpl

I have a map like this:

[FOOBAR:["FOOBAR"], \b(De(\w+))\b:["DELI", "DELEGATE"], SSN:["111-55-4444"]]

when I iterate the map and print class type of keys, I get this:

myMap.each{ k, v -> println "${k.class}:${v}" }
class java.lang.String:[FOOBAR]
class org.codehaus.groovy.runtime.GStringImpl:[DELI, DELEGATE]
class java.lang.String:[111-55-4444]

Question

How can I find the key with class GStringImpl?

I've tried the following but it doesn't work:

myMap[/\b(De(\w+))\b/] == ["DELI", "DELEGATE"]
|            |                 |
|            null              false
[FOOBAR:[FOOBAR], \b(De(\w+))\b:[DELI, DELEGATE], SSN:[111-55-4444]]

UPDATE: Based on comments

OP wanted to use a variable as key

Upvotes: 0

Views: 611

Answers (1)

Rao
Rao

Reputation: 21369

Here you go, it is just trivial, you need to put it in between (..).

change it from:

def myMap = [FOOBAR:["FOOBAR"], \b(De(\w+))\b:["DELI", "DELEGATE"], SSN:["111-55-4444"]]

to:

def userKey = 'key'
def myMap = [FOOBAR:["FOOBAR"], (userKey):["DELI", "DELEGATE"], SSN:["111-55-4444"]]

EDIT: updating more info.

Groovy accepts key without quotes and with quotes as well. So, if it is object, then needs to be wraped in between (..). It can be any object.

Upvotes: 1

Related Questions