Method One: Use entries in the For-each loop to traverse
This is the most common way to traverse, which is used when you need to get the key and value.
Map<integer, integer> map = new Hashmap<integer, integer> (); For (Map.entry<integer, integer> entry:map.entrySet ()) { System.out.println ("Key =" + entry.getkey () + ", Val UE = "+ Entry.getvalue ()); }
Note: The For-each loop is introduced in Java 5, so the method can only be applied to Java 5 or later. If you traverse an empty map object, the For-each loop will throw nullpointerexception, so you should always check for null references before traversing.
Method Two traverses the keys or values in the For-each loop.
If you only need the keys or values in the map, you can implement the traversal through keyset or values instead of using EntrySet.
Map<integer, integer> map = new Hashmap<integer, integer> (); Traverse the key for (Integer Key:map.keySet ()) { System.out.println ("key =" + key) in the map; } Traverse the value in map for (Integer value:map.values ()) { System.out.println ("value =" + value); }
Method three uses iterator traversal
Using generics:
Map<integer, integer> map = new Hashmap<integer, integer> (); Iterator<map.entry<integer, integer>> entries = Map.entryset (). Iterator (); while (Entries.hasnext ()) { Map.entry<integer, integer> Entry = Entries.next (); System.out.println ("Key =" + entry.getkey () + ", Value =" + Entry.getvalue ()); }
Do not use generics:
Map map = new HashMap (); Iterator entries = Map.entryset (). Iterator (); while (Entries.hasnext ()) { Map.entry Entry = (map.entry) entries.next (); Integer key = (integer) entry.getkey (); Integer value = (integer) entry.getvalue (); System.out.println ("key =" + key + ", value =" + value); }
This way of looking redundant has its advantages. First, this is the only way to traverse the map in the old version of Java. Another benefit is that you can delete the entries by calling Iterator.remove () over the duration, and the other two methods cannot. According to Javadoc, if you try to use this method in a For-each traversal, the result is unpredictable.
Method Four, through the key to find the value traversal (low efficiency)
Map<integer, integer> map = new Hashmap<integer, integer> (); For (integer Key:map.keySet ()) { integer value = map.get (key); System.out.println ("key =" + key + ", value =" + value); }
Choose according to the occasion.
Ways to traverse map objects in Java