How the Map collection in Java is traversed

Source: Internet
Author: User

Method One: Use entries in the For-each loop to traverse

1 New Hashmap<integer, integer>();   2   3  for (Map.entry<integer, integer> entry:map.entrySet ()) {  4   5     System.out.println ("Key =" + entry.getkey () + ", Value =" + Entry.getvalue ());   6   7 }  

Method Two: use iterator traversal

1Map<integer, integer> map =NewHashmap<integer, integer>();2 3Iterator<map.entry<integer, integer>> entries =Map.entryset (). iterator ();4 5  while(Entries.hasnext ()) {6 7Map.entry<integer, integer> Entry =Entries.next ();8 9System.out.println ("Key =" + entry.getkey () + ", Value =" +Entry.getvalue ());Ten  One}

The method also designs a design pattern, that is, iterative mode. This method can be called Iterator.remove () to delete entries during the time elapsed.

You can also not join generics:

1Map map =NewHashMap ();2 3Iterator entries =Map.entryset (). iterator ();4 5  while(Entries.hasnext ()) {6 7Map.entry Entry =(Map.entry) Entries.next ();8 9Integer key =(Integer) Entry.getkey ();Ten  OneInteger value =(Integer) entry.getvalue (); A  -System.out.println ("key =" + key + ", Value =" +value); -  the}

Method Three iterates through the values by a key set

1 New Hashmap<integer, integer>(); 2 3  for (Integer key:map.keySet ()) {45     Integer value = map.get (key); 6 7     System.out.println ("key =" + key + ", value =" + value "); 8 9 }

This method is inefficient and is not recommended for use

Method four The values () method

1Map<integer, integer> map =NewHashmap<integer, integer>();2 3 4  for(Integer key:map.keySet ()) {5 6System.out.println ("Key =" +key);7 8 }9Ten  for(Integer value:map.values ()) { One  ASystem.out.println ("Value =" +value); -  -}

How the Map collection in Java is traversed

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.