Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator over HashMap in Java

Tags:

I tried to iterate over hashmap in Java, which should be a fairly easy thing to do. However, the following code gives me some problems:

HashMap hm = new HashMap();

hm.put(0, "zero");
hm.put(1, "one");

Iterator iter = (Iterator) hm.keySet().iterator();

while(iter.hasNext()) {

    Map.Entry entry = (Map.Entry) iter.next();
    System.out.println(entry.getKey() + " - " + entry.getValue());

}

First, I needed to cast Iterator on hm.keySet().iterator(), because otherwise it said "Type mismatch: cannot convert from java.util.Iterator to Iterator". But then I get "The method hasNext() is undefined for the type Iterator", and "The method hasNext() is undefined for the type Iterator".

like image 451
cerebrou Avatar asked Mar 14 '13 23:03

cerebrou


People also ask

Can we use iterator with HashMap?

In Java HashMap, we can iterate through its keys, values, and key/value mappings.

Can we use iterator in Map in Java?

Remember that we cannot iterate over map directly using iterators, because Map interface is not the part of Collection. All maps in Java implements Map interface. There are following types of maps in Java: HashMap.


2 Answers

Can we see your import block? because it seems that you have imported the wrong Iterator class.

The one you should use is java.util.Iterator

To make sure, try:

java.util.Iterator iter = hm.keySet().iterator();

I personally suggest the following:

Map Declaration using Generics and declaration using the Interface Map<K,V> and instance creation using the desired implementation HashMap<K,V>

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

and for the loop:

for (Integer key : hm.keySet()) {
    System.out.println("Key = " + key + " - " + hm.get(key));
}

UPDATE 3/5/2015

Found out that iterating over the Entry set will be better performance wise:

for (Map.Entry<Integer, String> entry : hm.entrySet()) {
    Integer key = entry.getKey();
    String value = entry.getValue();

}

UPDATE 10/3/2017

For Java8 and streams, your solution will be (Thanks @Shihe Zhang)

 hm.forEach((key, value) -> System.out.println(key + ": " + value))
like image 167
Garis M Suero Avatar answered Oct 06 '22 08:10

Garis M Suero


You should really use generics and the enhanced for loop for this:

Map<Integer, String> hm = new HashMap<>();
hm.put(0, "zero");
hm.put(1, "one");

for (Integer key : hm.keySet()) {
    System.out.println(key);
    System.out.println(hm.get(key));
}

http://ideone.com/sx3F0K

Or the entrySet() version:

Map<Integer, String> hm = new HashMap<>();
hm.put(0, "zero");
hm.put(1, "one");

for (Map.Entry<Integer, String> e : hm.entrySet()) {
    System.out.println(e.getKey());
    System.out.println(e.getValue());
}
like image 27
millimoose Avatar answered Oct 06 '22 07:10

millimoose