Four traversal methods of the Map set and four map sets
Compare the code written a long time ago with the previous one! Easy to view later
1 import java. util. hashMap; 2 import java. util. iterator; 3 import java. util. map; 4 5 public class TestMap {6 public static void main (String [] args) {7 Map <Integer, String> map = new HashMap <Integer, String> (); 8 map. put (1, "a"); 9 map. put (2, "B"); 10 map. put (3, "AB"); 11 map. put (4, "AB"); 12 map. put (4, "AB"); // same as above, 13 System will be filtered by yourself. out. println (map. size (); 14 // type 1: 15/* 16 * Set <Integer> set = map. KeySet (); // obtain the set of all keys 17*18 * for (Integer in: set) {String str = map. get (in); 19 * System. out. println (in + "" + str);} 20 */21 System. out. println ("type 1: Map. keySet traversal key and value: "); 22 for (Integer in: map. keySet () {23 // map. keySet () returns the value of all keys 24 String str = map. get (in); // obtain the value of the value 25 System for multiple pairs of each key. out. println (in + "" + str); 26} 27 // type 2: 28 System. out. println ("Type 2: Map. entrySet uses iterator to traverse Key and value: "); 29 Iterator <Map. entry <Integer, String> it = map. entrySet (). iterator (); 30 while (it. hasNext () {31 Map. entry <Integer, String> entry = it. next (); 32 System. out. println ("key =" + entry. getKey () + "and value =" + entry. getValue (); 33} 34 // Type 3: Recommended, especially 35 systems with large capacity. out. println ("3: using Map. entrySet traverses key and value "); 36 for (Map. entry <Integer, String> entry: map. entrySet () {37 // Map. entry <Integ Er, String> ing (key-Value Pair) has several methods: Use the above name entry38 // entry. getKey (); entry. getValue (); entry. setValue (); 39 // map. entrySet () returns the Set view of the ing contained in the ing. 40 System. out. println ("key =" + entry. getKey () + "and value =" 41 + entry. getValue (); 42} 43 // type 4: 44 System. out. println ("type 4: Map. values () traverses all values, but cannot Traverse key "); 45 for (String v: map. values () {46 System. out. println ("value =" + v); 47} 48} 49}