1 Public Static voidMain (string[] args) {2 3 4map<string, string> map =NewHashmap<string, string>();5Map.put ("1", "value1");6Map.put ("2", "value2");7Map.put ("3", "Value3");8 9 //The first type: Universal use, two-time valueTenSystem.out.println ("Traverse key and value through Map.keyset:"); One for(String key:map.keySet ()) { ASystem.out.println ("key=" + key + "and value=" +Map.get (key)); - } - the //The second Kind -System.out.println ("Using Iterator to traverse key and value through Map.entryset":); -Iterator<map.entry<string, string>> it =Map.entryset (). iterator (); - while(It.hasnext ()) { +map.entry<string, string> Entry =It.next (); -System.out.println ("key=" + entry.getkey () + "and value=" +Entry.getvalue ()); + } A at //the third type: recommended, especially when the capacity is large -System.out.println ("Traverse key and value through Map.entryset"); - for(Map.entry<string, string>Entry:map.entrySet ()) { -System.out.println ("key=" + entry.getkey () + "and value=" +Entry.getvalue ()); - } - in //Fourth Type -System.out.println ("Traverse all value through Map.values (), but cannot traverse key"); to for(String v:map.values ()) { +System.out.println ("value=" +v); - } the}
Four ways to traverse a map