Iteration of the map collection in Java

Source: Internet
Author: User

ImportJava.util.HashMap;ImportJava.util.Iterator;ImportJava.util.Map; Public classTestMap { Public Static voidMain (string[] args) {Map<integer, string> map =NewHashmap<integer, string>(); Map.put (1, "a"); Map.put (2, "B"); Map.put (3, "AB"); Map.put (4, "AB"); Map.put (4, "AB");//same as above, will filter by itselfSystem.out.println (Map.size ()); //The first type:        /** set<integer> set = Map.keyset ();//Get a collection of all keys * * for (Integer in:set) {String St         R = Map.get (in); * SYSTEM.OUT.PRINTLN (In + "" + str);}*/System.out.println ("First: Traverse key and value through Map.keyset:");  for(Integer in:map.keySet ()) {//Map.keyset () returns the value of all keysString str = Map.get (in);//get the value of multiple pairs with value for each keySystem.out.println (In + "" +str); }        //The second type:System.out.println ("Second type: Using iterator to traverse key and value through Map.entryset":); Iterator<map.entry<integer, string>> it =Map.entryset (). iterator ();  while(It.hasnext ()) {Map.entry<integer, string> entry =It.next (); System.out.println ("Key=" + entry.getkey () + "and value=" +Entry.getvalue ()); }        //the third type: recommended, especially when the capacity is largeSystem.out.println ("Third: traversal of key and value through Map.entryset");  for(Map.entry<integer, string>Entry:map.entrySet ()) {            //There are several ways to map.entry<integer,string> mapping entries (key-value pairs): Use the name above entry//Entry.getkey (); Entry.getvalue (); Entry.setvalue (); //Map.entryset () returns the set view of the mapping relationships contained in this map. System.out.println ("key=" + entry.getkey () + "and value=" +Entry.getvalue ()); }        //The fourth type:System.out.println ("Fourth: Traverse all the value through Map.values (), but cannot traverse key");  for(String v:map.values ()) {System.out.println ("Value=" +v); }    }}

Iteration of the map collection in Java

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.