How to iterate through a Map in Java?

Source: Internet
Author: User

1.Iterate through the "EntrySet" like so:

 Public Static void Printmap (Map MP) {    = mp.entryset (). iterator ();      while (It.hasnext ()) {        = (map.entry) It.next ();         + "=" + Pair.getvalue ());         // avoids a concurrentmodificationexception     }}

2.If interested in the keys and you can iterate through the "KeySet ()" of the map:

map<string, object> map = ...;  for (String key:map.keySet ()) {    //  ...}

3.If need the values, use "value ()":

 for (Object value:map.values ()) {    //  ...}

4.Finally, if you want both the key and value, use "EntrySet ()":

 for (map.entry<string, object> entry:map.entrySet ()) {    = entry.getkey ();     = Entry.getvalue ();     //  ...}

Summary,if need only keys or values from the map, use method #2 or method #3. If you is stuck with older version of Java (less than 5) or planning to remove entries during iteration Method #1. Otherwise use Method #4.

How to iterate through a Map in Java?

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.