1

I have a question about iterate a hashmap:

Map<String, Integer> map = new HashMap<String, Integer>();

I want to iterate this hashmap and printout out the key and value pair using the following code:

Iterator iterator = portMap.keySet().iterator();

but it indicates me to cast the portMap.keySet().iterator(); to (Iterator)portMap.keySet().iterator();, but the iterator() return as a iterator already, why I need to cast it? And I checked some other code, there is no cast for the return value of iterator(), what is the reason, and how to fix it?

ratzip
  • 113
  • 2
  • 11
  • 2
    is it intentional that `map` and `portMap` are different? – Ross Drew Feb 05 '14 at 14:09
  • Is there any errors? I guess your IDE would just be showing a warning (yellow underline in eclipse), that's because whats returned could be Iterator and you are assigning it to Iterator – Dhana Krishnasamy Feb 05 '14 at 14:12

2 Answers2

5

If you want to print the keys AND the values, you should use entrySet instead:

for (Map.Entry<String, Integer> e : map.entrySet()) {
    System.out.println(e.getKey() + " = " + e.getValue());
}

As for your casting issue, it may be because you are importing a different Iterator class in your imports. With the correct imports, this compiles fine without casting:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

//.....

Map<String, Integer> map = new HashMap<String, Integer>();
Iterator<String> iterator = map.keySet().iterator();
assylias
  • 321,522
  • 82
  • 660
  • 783
0

You can use the enhanced loop in the following way:

for (Entry entry :  map.entrySet()) {
    System.out.format("%s , %s\n", entry.getKey(), entry.getValue());
}

so like this you loop over all entries of the map. In the import section you should have the following import of the Entry

import java.util.Map.Entry;

hence the complete imports section would look like this:

import java.util.HashMap;
import java.util.Map;

import java.util.Map.Entry;

If you want to go over the keys and extract the corresponding value for each of them you can go the following way:

import java.util.HashMap;
import java.util.Map;
// ...
for (String s : map.keySet()) {
   System.out.format("%s , %s\n", s, map.get(s));
}

If you want to use an iterator and loop over the keys and extracting from the map based on the key:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
//...

Iterator<String> it = map.keySet().iterator();

while (it.hasNext()){
   String currentKey = it.next();
   System.out.format("%s , %s\n", currentKey), map.get(currentKey));
}

I hope these help you.

Olimpiu POP
  • 5,001
  • 4
  • 34
  • 49