Java map traversal methods: javamap

Source: Internet
Author: User

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 ());}}}


 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.