Three ways to traverse map in Java

Source: Internet
Author: User

three ways to traverse map:1. Use keyset traversal, while loop;2. Use EntrySet traversal, while loop;3. Use for loop traversal. tell you a little secret: (The next ↓ is the test code, most love to see the code, wordy and more useless) people I don't tell him oh.
Import java.util.*;
//0 my main interfacepublic class Maptraverse {public static void main (string[] args) {string[] str = {' I love you ', ' You love he ', ' he love he ' R "," She Love Me "}; Map<integer, string> m = new HashMap (); for (int i=0; i<str.length; i++) {m.put (I, Str[i]);} System.out.println ("1. Using keyset traversal, while loop"); Myketset (m); System.out.println ("2. Using EntrySet traversal, while loop"); Myentryset (m); System.out.println ("3. Use for loop traversal"); Myfor (m);}

//1 My Myketset () methodpublic static void Myketset (Map<integer, string> m) {Set s = (set<integer>) m.keyset (); Iterator<integer > it = s.iterator (); int Key; String Value;while (It.hasnext ()) {Key = It.next (); value = (String) m.get (key); System.out.println (key+ ": \ T" +value);}}

//2 my Myentryset () methodpublic static void Myentryset (Map m) {Set s = m.entryset (); Iterator<map.entry<integer, string>> it = S.iterato R (); Map.entry<integer, string> entry;int Key; String Value;while (It.hasnext ()) {entry = It.next (); Key = Entry.getkey (); value = Entry.getvalue (); System.out.println (key+ ": \ T" +value);}}

//3 My Myfor () methodpublic static void Myfor (Map<integer, string> m) {int Key; String value;for (Map.entry<integer, string> entry:m.entryset ()) {Key = Entry.getkey (); value = Entry.getvalue (); System.out.println (key+ ": \ T" +value);}}}



Copyright Notice:This article for Bo Master original article, without Bo Master permission not reproduced



Three ways to traverse 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.