Three map traversal methods!
A very important operation of the Set-traversal. I learned three traversal methods, each of which has its own advantages and disadvantages ~~
The Code is as follows:
Package CN. tsp2c. liubao;
Import java. util. collection;
Import java. util. hashmap;
Import java. util. iterator;
Import java. util. Map;
Import java. util. Set;
Import java. util. treemap;
/**
*
* @ Author LHY
*/
Public class testmap {
Public static void main (string [] ARGs ){
Map <string, student> map = new hashmap <string, student> ();
Student S1 = new student ("", "1001", 38 );
Student S2 = new student ("Lu Junyi", "1002", 35 );
Student S3 = new student ("Wu Yong", "1003", 34 );
Map. Put ("1001", S1 );
Map. Put ("1002", S2 );
Map. Put ("1003", S3 );
Map <string, student> submap = new hashmap <string, student> ();
Submap. Put ("1008", new student ("Tom", "1008", 12 ));
Submap. Put ("1009", new student ("Jerry", "1009", 10 ));
Map. putall (submap );
Work (MAP );
Workbykeyset (MAP );
Workbyentry (MAP );
}
// The most common Traversal method. The most common method is the most commonly used method. Although it is not complex, it is very important. This is what we are most familiar with. I will not talk about it much !!
Public static void work (Map <string, student> map ){
Collection <student> C = map. Values ();
Iterator it = C. iterator ();
For (; it. hasnext ();){
System. Out. println (it. Next ());
}
}
// Use keyset for traversal. Its advantage is that it can be worth the values you want based on the key you want, making it more flexible !!
Public static void workbykeyset (Map <string, student> map ){
Set <string> key = map. keyset ();
For (iterator it = key. iterator (); it. hasnext ();){
String S = (string) it. Next ();
System. Out. println (Map. Get (s ));
}
}
// A complicated Traversal method is provided here ~~ He is very violent. He is so flexible that he can get whatever he wants ~~
Public static void workbyentry (Map <string, student> map ){
Set <map. Entry <string, student> set = map. entryset ();
For (iterator <map. Entry <string, student> it = set. iterator (); it. hasnext ();){
Map. Entry <string, student> entry = (Map. Entry <string, student>) it. Next ();
System. Out. println (entry. getkey () + "--->" + entry. getvalue ());
}
}
}