Java map traversal methods: javamap
1.1. Get value through key
// Obtain all key values Set <String> keySet =Map. keySet (); // Calculate the value based on the key. For(String key: keySet ){ System.Out. Println (key + ":" + map. get (key )); } |
1.2. Get the key and value through the entry
// Obtain all the entries Set <Entry <String, String> entrySet =Map. entrySet (); // Obtain the key and value values from the entry. For(Entry <String, String> entry: entrySet ){ System.Out. Println (entry. getKey () + ":" + entry. getValue ()); } |
1.3. Complete sample code
MapTest. java |
Package map; import java. util. hashMap; import java. util. map; import java. util. map. entry; import java. util. set; import org. junit. beforeClass; import org. junit. test; publicclass MapTest {private Map map; @ BeforeClass publicvoid init () {map = new HashMap <String, String> (); map. put ("1", "Morris"); map. put ("2", "Jack"); map. put ("3", "Bob"); map. put ("4", "Tom") ;}@ Test publicvoid traversal1 () {// obtain all key values Set <String> keySet = map. keySet (); // value for (String key: keySet) {System. out. println (key + ":" + map. get (key) ;}@ Test publicvoid traversal2 () {// obtain all entry sets <Entry <String, String> entrySet = map. entrySet (); // obtain the key and value from the entry for (Entry <String, String> entry: entrySet) {System. out. println (entry. getKey () + ":" + entry. getValue ());}}}
|