Traverse hashmap Hashmap attmap; Iterator I = attmap. entryset (). iterator (); While (I. hasnext ()){
Object o = I. Next ();
String key = O. tostring ();
// You can traverse the key value of the hashmap. } Of course, you can also traverse map. Entry items and values. The method is similar.
Yes.
Object [] obja = attmap. keyset (). toarray ();
According to our support, it is faster to use entryset to traverse hashmap, because most of them use keyset to traverse and do not think so much. I studied it today, but it is actually a lot worse.
See the example for a simple hashmap. If you run this class locally, you can easily see the result.
Import java. util. hashmap;
Import java. util. iterator;
Import java. util. calendar;
Public class hashmaptest {
Public static void main (string [] ARGs ){
Hashmap = new hashmap ();
For (INT I = 0; I <1000; I ++ ){
Hashmap. Put ("" + I, "hello ");
}
Long BS = calendar. getinstance (). gettimeinmillis ();
Iterator = hashmap. keyset (). iterator ();
// String value = "";
While (iterator. hasnext ()){
// Value = hashmap. Get (iterator. Next ());
System. Out. println (hashmap. Get (iterator. Next ()));
}
System. Out. println (calendar. getinstance (). gettimeinmillis ()-BS );
Listhashmap ();
}
Public static void listhashmap (){
Java. util. hashmap = new java. util. hashmap ();
For (INT I = 0; I <1000; I ++ ){
Hashmap. Put ("" + I, "hello ");
}
Long BS = calendar. getinstance (). gettimeinmillis ();
// Set = hashmap. entryset ();
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. println (entry. getvalue ());
}
System. Out. println (calendar. getinstance (). gettimeinmillis ()-BS );
}
}
for keyset, the key is traversed twice, converted to iterator at one time, and the value of key is retrieved from hashmap at one time.
however, entryset is the first traversal, he puts both the key and value in the entry, so it's faster.
for Web applications, some of them may use VO objects or form to encapsulate information. Therefore, when hashmap is used, the above objects are stored in it. Therefore, the traversal performance using entryset is improved.
many hashmaps are used, for example, you need to use the imported information. Because most of the imported information must be used to determine whether duplicate information exists, you can use containskey for processing instead of processing it during insertion.