First:
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 ();
}
High efficiency. You must use this method in the future!
Second:
Map map = new HashMap ();
Iterator iter = map. keySet (). iterator ();
While (iter. hasNext ()){
Object key = iter. next ();
Object val = map. get (key );
}
Low efficiency. Try to use less in the future!
There are two common methods for HashMap traversal: Using keyset and entryset for traversal, but the traversal speed of the two is different. See the example below:
Public class HashMapTest {
Public static void main (String [] args )...{
HashMap hashmap = new HashMap ();
For (int I = 0; I <1000; 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 <1000; 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 item.
// Entry. getValue () returns the value corresponding to this item.
System. out. print (entry. getValue ());
}
System. out. println ();
System. out. println (Calendar. getInstance (). getTimeInMillis ()-bs );
}
}
The keySet is actually traversed twice. Once converted to iterator, the key pair value is retrieved from the hashmap at one time. However, entryset only traverses the data for the first time. It puts both the key and value into the entry, so it's faster.
Note: The Hashtable Traversal method is similar to the above one!