Summary of the four methods of Java map traversal

  • 2020-04-01 02:22:43
  • OfStack

Four methods for traversing maps in Java are summarized:

Import the Java. Util. HashMap; Import the Java. Util. Iterator; Import the Java. Util. The Map; Import the Java. Util. Map. Entry; Import the Java. Util. Set; PublicclassMapTest {privateMap< String, String> The map; PublicMapTest () {
    The map = newHashMap< String, String> (a);
    Map.put ("1"," first number ");
    Map.put ("2"," second number ");
    Map.put ("3"," third number "); }// first method (traditional method) publicvoid mapOne(){Set< String> The set = map. KeySet (); Iterator< String> It = set. The iterator (); While (it. HasNext ()) {String key = (String) it. Next (); String value = (String) map. Get (key); System. The out. Println (" = "key + + value); }}// the second method (traditional method) publicvoid mapTwo(){Set Set = map.entryset (); The Iterator it = set. The Iterator (); While (it. HasNext ()) {Entry Entry = (Entry) it. Next (); The String key = (String) entry. GetKey (); String value = (String) entry. The getValue (); System. The out. Println (" = "key + + value); }}// the third method (enhanced for loop method) publicvoid mapThree(){for(Object obj: map.keyset ()){String key =(String) obj; String value = (String) map. Get (key); System. The out. Println (" = "key + + value); }}// the fourth method (enhanced for loop method) publicvoid mapFour(){for(Object obj: map.entryset ()){Entry Entry =(Entry) obj; The String key = (String) entry. GetKey (); String value = (String) entry. The getValue (); System. The out. Println (" = "key + + value); }publicstaticvoid main(String[] args){MapTest MapTest =newMapTest(); System. The out. Println (" = = = = = first = = = = = ");
    MapTest. MapOne (); System. The out. Println (" = = = = = second = = = = = ");
    MapTest. MapTwo (); System. The out. Println (" = = = = = three = = = = = ");
    MapTest. MapThree (); System. The out. Println (" = = = = = four = = = = = ");
    MapTest. MapFour (); }} output result:

= = = = = first = = = = = 3 = 3 number 2 = the second number the first number 1 = = = = = = second = = = = = 3 = 3 number 2 = the second number the first number 1 = = = = = = three = = = = = 3 = 3 number 2 = the second number the first number 1 = = = = = = four = = = = = 3 = 3 number 1 = 2 = the second number the first number


Related articles: