AbuMariam AbuMariam - 1 year ago 226
Groovy Question

Groovy: How to check if a given String is a key of a Map?

I am reading from a file into a Map like so...

def inputFile = new File("/Users/joe/Desktop/teamManagers.txt");
def teams = [:]

inputFile.eachLine { rawLine ->
def line = rawLine.split('\t')

String team = line[0].toString()
def manager = line[1]
teams.put(team, manager)

println ("${team} has hash code ${team.hashCode()}")


One of the values I am putting in the map is "Yankees". And so the last line prints out

"Yankees" has hash code -1687935690

But now if I want to check if this String is in the Map, it seems to have a different hash code. For example this code..

println "Yankees".hashCode();

prints out 265351886. As you can see this is different from the hashcode of the same String when it was pulled out of the file.

Why is it behaving this way? Shouldn't two equal Strings have the same hashcode?

How can I check if a given String is in the Map?

Answer Source

Apparently, your file has Yankees in quotes (as seen in your output as well)

For me, this code:

def team ='"Yankees"'
println ("${team} has hash code ${team.hashCode()}")
println "Yankees".hashCode()​

gives this output:

"Yankees" has hash code -1687935690

Which is consistent with your results.

This however

def team ='"Yankees"'
println ("${team} has hash code ${team.hashCode()}")
println '"Yankees"'.hashCode()​

gives same hash. So theres your problem

EDIT: you also asked how to tell if a key is in a map. You can do if(map["Im a key!"]) for example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download