Two ways to HashMap traversal in Java
Original address: http://www.javaweb.cc/language/java/032291.shtml
The first type:
Map map = new HashMap ();
Iterator iter = Map.entryset (). Iterator ();
while (Iter.hasnext ()) {
Map.entry Entry = (map.entry) iter.next ();
Object key = Entry.getkey ();
Object val = Entry.getvalue ();
}
The efficiency is high, must use this kind of way later!
The second type:
Map map = new HashMap ();
Iterator iter = Map.keyset (). Iterator ();
while (Iter.hasnext ()) {
Object key = Iter.next ();
Object val = map.get (key);
}
Low efficiency, use less in the future!
HASHMAP traversal has two common methods, that is, using keyset and entryset to traverse, but the two traverse speed is different, see the example below:
public class Hashmaptest {
public static void Main (string[] args) ... {
HashMap HashMap = new HashMap ();
for (int i = 0; i <; i) ... {
Hashmap.put ("" I, "thanks");
}
Long bs = Calendar.getinstance (). Gettimeinmillis ();
Iterator Iterator = Hashmap.keyset (). Iterator ();
while (Iterator.hasnext ()) ... {
System.out.print (Hashmap.get (Iterator.next ()));
}
System.out.println ();
System.out.println (Calendar.getinstance (). Gettimeinmillis ()-BS);
Listhashmap ();
}
public static void Listhashmap () ... {
Java.util.HashMap HashMap = new Java.util.HashMap ();
for (int i = 0; i <; i) ... {
Hashmap.put ("" I, "thanks");
}
Long bs = Calendar.getinstance (). Gettimeinmillis ();
Java.util.Iterator it = Hashmap.entryset (). Iterator ();
while (It.hasnext ()) ... {
Java.util.Map.Entry Entry = (java.util.Map.Entry) it.next ();
Entry.getkey () returns the key corresponding to this key
Entry.getvalue () returns the value corresponding to this key
System.out.print (Entry.getvalue ());
}
System.out.println ();
System.out.println (Calendar.getinstance (). Gettimeinmillis ()-BS);
}
}
For keyset is actually traversed 2 times, one is converted to iterator, one time from the HashMap to remove the value of key. And EntrySet just traversed the first time, he put the key and value in the entry, so soon.
Two ways of HashMap traversal in Java (this tutorial is for research and learning only, not for the Java Chinese web view)
This article link address: http://www.javaweb.cc/language/java/032291.shtml
If you want to reprint, please specify from Java Chinese network: http://www.javaweb.cc/
Two ways of HashMap traversal in Java