The HashMap store is a key-value pair, so its traversal with the list and set should be different in general.
But Java cleverly handles HashMap's key-value pairs as a monolithic object (Java.util.Map.Entry), which optimizes the traversal of the hashmap, making it no different from the list and set.
The first type:
Java code
- Map map = new HashMap ();
- Iterator iter = Map.entryset (). Iterator ();
- while (Iter.hasnext ()) {
- Java.util.Map.Entry Entry = (map.entry) iter.next ();
- Object key = Entry.getkey ();
- Object val = Entry.getvalue ();
- }
The second type:
Java code
- Map map = new HashMap ();
- Iterator iter = Map.keyset (). Iterator ();
- while (Iter.hasnext ()) {
- Object key = Iter.next ();
- Object val = map.get (key);
- }
For example:HASHMAP traversal has two common methods, that is to use keyset and entryset to traverse, but the two traverse speed is different, see the example: Java code
- public class Hashmaptest {
- public static void Main (string[] args) ... {
- HashMap HashMap = new HashMap ();
- for (int i = 0; i <; i) ... {
- Hashmap.put ("I," that's All ");
- }
- Long num = 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 ()-num);
- Listhashmap ();
- }
- public static void Listhashmap () ... {
- Java.util.HashMap HashMap = new Java.util.HashMap ();
- for (int i = 0; i <; i) ... {
- Hashmap.put ("I," that's All ");
- }
- Long num = 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 ()-num);
- }
- }
Look at the JDK source code, compare two ways of access:
First look at keyset access mode:
Java code
- Public set<k> KeySet () {
- if (KeySet = = null) {
- KeySet = new Abstractset<k> () {
- Public iterator<k> Iterator () {
- return new iterator<k> () {
- Private Iterator<entry<k,v>> i = EntrySet (). Iterator ();
- public Boolean hasnext () {
- return I.hasnext ();
- }
- Public K Next () {
- Return I.next (). GetKey ();
- }
- public void Remove () {
- I.remove ();
- }
- };
- }
- public int size () {
- return AbstractMap.this.size ();
- }
- Public Boolean contains (Object k) {
- Return AbstractMap.this.containsKey (k);
- }
- };
- }
- return keySet;
- }
Conclusion:Through the above test we can see that the use of entryset-way traversal efficiency is better than keyset, so in the development to use EntrySet, try to avoid less use keyset.
Cautious use of keyset: Comparison of 2 traversal modes for HASHMAP