Summary of four methods of Java map traversal

Four methods of map traversal in Java are sorted out:

import java. util. HashMap; import java. util. Iterator; import java. util. Map; import java. util. Map. Entry; import java. util. Set; Publicclassmaptest {privatemap < string, string > map; publicmaptest() {map = newhashmap < string, string > (); map.put ("1", "first number"); map.put ("2", "second number"); map.put ("3", "third number");}// The first method (traditional method) is publicvoid mapone() {set < string > set = map. Keyset(); iterator < string > it = set. Iterator(); while (it. Hasnext()) {string key = (string) it. Next(); string value = (string) map. Get (key); system. Out. Println (Key + "=" + value);}}// The second method (traditional method) is publicvoid maptwo() {set set = map. Entryset(); iterator it = set. Iterator(); while (it. Hasnext()) {entry = (entry) it. Next(); string key = (string) entry. Getkey(); string value = (string) entry. Getvalue(); system. 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.out.println (Key + "=" + value);}}// The fourth method (enhanced for loop method) publicvoid mapfour() {for (object obj: map. Entryset()) {entry = (entry) obj; string key = (string) entry. Getkey(); string value = (string) entry. Getvalue(); system.out.println (Key + "=" + value);}} publicstaticvoid main(String[] args){MapTest mapTest =newMaptest();System.out.println("=====first====="); mapTest.mapOne();System.out.println("=====second====="); mapTest.mapTwo();System.out.println("=====three====="); mapTest.mapThree();System.out.println("=====four====="); mapTest.mapFour();}} Output results:

=====First ====== 3 = the third number 2 = the second number 1 = the first number ====== second ======== 3 = the third number 2 = the second number 1 = the first number ======= 3 = the third number 2 = the second number 1 = the first number ====== four ====== 3 = the third number 2 = the second number 1 = the first number

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>