"Java Programming" uses an enhanced for loop and an iterator to traverse the map collection __ algorithm

Source: Internet
Author: User
1, through the key set access, to key interest, you can access the value corresponding to the key;

For (String K:maps.keyset ()) {
            System.out.println (k +: +maps.get);
        }

2, through the value set access, only the value of interest, can not access the key value;

For (String value:maps.values ()) {
            System.out.println (value);
        }

3, through entry collection access, interested in entry, you can access the value corresponding to the key

For (Entry Entry:maps.entrySet ()) {
            System.out.println (Entry.getkey () + ":" +entry.getvalue ());
        }

4, through the iteration key set to access the Map collection, Maps.keyset () returns a Set<string> collection, the set directly inherits collection, so you can iterate over it.

Iterator<string> iterator = Maps.keyset (). iterator ();
        while (Iterator.hasnext ()) {
            String key = Iterator.next ();
            System.out.println (key+ ":" +maps.get (key));
        }

5. Access to the map collection through the iteration values collection, Maps.values () returns the Collection<string>, so you can iterate over it.

Iterator<string> iter= maps.values (). iterator ();
        while (Iter.hasnext ()) {
            System.out.println (Iter.next ());
        }

6, through the iterative Entry collection to access the Map collection, Maps.entryset () returns a set<entry<string, String>>,set directly inherit collection, so you can iterate over it.

Iterator<entry<string, string>> it = Maps.entryset (). iterator ();
        while (It.hasnext ()) {
            entry<string, string> Entry = It.next ();
            System.out.println (Entry.getkey () + ":" +entry.getvalue ());
        }

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.