Summary of the traversal of the Map set and the summary of the map set

Source: Internet
Author: User

Summary of the traversal of the Map set and the summary of the map set

The traversal of a Map set is often encountered. Today we will summarize several methods of traversing a Map set:

1 public static void main (String [] args) {2 Map <String, String> map = new HashMap <String, String> (); 3 map. put ("1", "Zhang San"); 4 map. put ("2", "Li Si"); 5 map. put ("3", "Wang Wu"); 6 7}

 

1 for (String key: map. keySet () {2 System. out. print ("key =" + key); 3 System. out. println ("value =" + map. get (key); 4 5}View Code

2. Traverse Map through Map. entrySet and iterator

Iterator<Map.Entry<String,String>> car =map.entrySet().interator();  while(car.hasNext()){      Map.Entry<String,String>  entry=car.next();     System.out.println("key="+entry.getKey()+"and value="+entry.getValue());  }

3. Map. entrySet () plus for in loop (recommended ):

for(Map.Entry<String,String> entry:map.entrySet()){    System.out.println("key="+entry.getKey()+"and value="+entry.getValue());}

Note: Map. entrySet () returns a Set <Map <k, v>, Map. an Entry is an interface that represents a key-Value Pair (ing item), and Set <Map <k, v> indicates the Set of the ing item.

4. Map. values ():

for(String val:map.Values()){    System.out.println("value="+v);}

 

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.