The following is a list of some of the most commonly used Java traversal map object methods
1. Using EntrySet traversal in For-each
This is the most common way to traverse. Used when the key value is required.
new HashMap<String,String>();for(Map.Entry<String, String> entry : map.entrySet()){ System.out.println(entry.getKey()+" : "+entry.getValue());}
2. Traverse 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.
new HashMap<String,String>();for(String key : map.keySet()){ System.out.println("key: " + key);}for(String value : map.values()){ System.out.println("value: " + value);}
3. Using iterator traversal
new HashMap<String,String>();Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();while(iterator.hasNext()){ Map.Entry<String, String> m = iterator.next(); " : "+m.getValue());}
Using this method to call Iterator.remove () during a time-out can remove entries, other methods cannot, and may produce unexpected results.
Reference: Links
4. Traverse value via key
new HashMap<String,String>();for(String key : map.keySet()){ String value = map.get(key); " : " +value);}
Cases:
ImportJava.util.HashMap;ImportJava.util.Iterator;ImportJava.util.Map; Public class T { Public Static void Main(string[] args) {map<string, string> Map =NewHashmap<string, string> (); Map.put ("Beijing","Kaoya"); Map.put ("Henan","Hulatang"); Map.put ("Tianjin","Mahua"); System.out.println ("1, using EntrySet traversal in For-each"); for(Map.entry<string, String> entry:map.entrySet ()) {System.out.println (Entry.getkey () +" : "+ Entry.getvalue ()); } System.out.println ("2. Traverse keys or values in the For-each loop"); for(String Key:map.keySet ()) {System.out.println ("key:"+ key); } for(String value:map.values ()) {System.out.println ("Value:"+ value); } System.out.println ("3, using iterator traversal"); iterator<map.entry<string, string>> ite = Map.entryset (). Iterator (); while(Ite.hasnext ()) {map.entry<string, string> m = Ite.next (); System.out.println (M.getkey () +" : "+ M.getvalue ()); } System.out.println ("4, Traverse value through key"); for(String Key:map.keySet ()) {String value = Map.get (key); SYSTEM.OUT.PRINTLN (key +" : "+ value); } }}
Itmyhome
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Traversing a Map object in Java