Four ways to traverse a map

Source: Internet
Author: User

Four ways to traverse a map

 Public classMaptest { Public Static voidMain (string[] args) {Map<string, string> maps =NewHashmap<string, string>(); Maps.put ("K1", "value1"); Maps.put ("K2", "value2"); Maps.put ("K3", "Value3"); Test1 (maps);//test2 (maps);//test3 (maps);//test4 (maps);    }        //The first type: Universal use, two-time value     Public Static voidTest1 (map<string, string>maps) {System.err.println ("Traversing key and value through Map.keyset");  for(String key:maps.keySet ()) {System.out.println ("Key:" +key+ "--->value:" +Maps.get (key)); }    }        //The second type: Use iterator to traverse key and value via Map.entryset     Public Static voidTest2 (map<string, string>maps) {System.err.println ("Using iterator to traverse key and value through Map.entryset:"); Iterator<map.entry<string, string>> it =Maps.entryset (). iterator ();  while(It.hasnext ()) {Map.entry<string, string> entry =It.next (); System.out.println ("Key:" +entry.getkey () + "--->value:" +Entry.getvalue ()); }    }        //the third type: recommended, especially when the capacity is large     Public Static voidTest3 (map<string, string>maps) {System.err.println ("Traversing key and value through Map.entryset");  for(Map.entry<string, string>Entry:maps.entrySet ()) {System.out.println ("Key:" +entry.getkey () + "--->value:" +Entry.getvalue ()); }    }        //Fourth Type         Public Static voidTest4 (map<string, string>maps) {System.out.println ("Traverse all value through Map.values (), but cannot traverse key");  for(String str:maps.values ()) {System.out.println ("Value:" +str); }        }}

Four ways to traverse a map

Related Article

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.