Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems looping over a HashMap<String, String>

Tags:

java

hashmap

I've got a basic HashMap. I'm trying to loop over it and get both the key and the value out of the Map. Here's what I have:

Map<String, String> myMap = versionExtractor.getVersionInfo();
for(String key : myMap.keySet())
    System.out.println(key);
    System.out.println(myMap.get(key));
}

The problem is that this won't compile. There is an error on the line that says System.out.println(myMap.get(key)); that says:

java: class, interface, or enum expected

And the intelliJ IDE says: Cannot resolve symbol 'key'. The perplexing thing is that is resolved key without a problem in the preceding line that says System.out.println(key);. What's up with that?

like image 225
quakkels Avatar asked Sep 23 '26 14:09

quakkels


1 Answers

Instead of myMap[key], you should use myMap.get(key). It's a Map, not an array. BTW, if you want both key and value, you can rather iterate over the EntrySet:

for (Entry<String, String> entry: myMap.entrySet()) {
    System.out.println(entry.getKey());
    System.out.println(entry.getValue());
}

This saves extra hash calculation, and lookup on every iteration.


As it goes, the issue is something else. The missing { brace after your for statement, makes the closing } of for loop extraneous. Anyways, my original answer was with regards to your original question which used myMap[key] instead.

like image 147
Rohit Jain Avatar answered Sep 26 '26 04:09

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!