How Java Map traverses

Source: Internet
Author: User

Several methods of traversing map in Java
Java code
Map<string,string> map=new hashmap<string,string> ();
Map.put ("username", "QQ");
Map.put ("PassWord", "123");
Map.put ("UserID", "1");
Map.put ("Email", "[email protected]");
Map<string,string> map=new hashmap<string,string> ();
Map.put ("username", "QQ");
Map.put ("PassWord", "123");
Map.put ("UserID", "1");
Map.put ("Email", "[email protected]");
The first with a For loop
Java code

For (map.entry<string, string> entry:map.entrySet ()) {
System.out.println (Entry.getkey () + "--->" +entry.getvalue ());
}
For (map.entry<string, string> entry:map.entrySet ()) {
System.out.println (Entry.getkey () + "--->" +entry.getvalue ());
}

Iteration of the second use
Java code

Set set = Map.entryset ();
Iterator i = Set.iterator ();
while (I.hasnext ()) {
Map.entry<string, string> entry1= (map.entry<string, string>) I.next ();
System.out.println (Entry1.getkey () + "= =" +entry1.getvalue ());
}
Set set = Map.entryset ();
Iterator i = Set.iterator ();
while (I.hasnext ()) {
Map.entry<string, string> entry1= (map.entry<string, string>) I.next ();
System.out.println (Entry1.getkey () + "= =" +entry1.getvalue ());
}
Using keyset () iteration
Java code

Iterator It=map.keyset (). Iterator ();
while (It.hasnext ()) {
String key;
String value;
Key=it.next (). toString ();
Value=map.get (key);
System.out.println (key+ "--" +value);
}
Iterator It=map.keyset (). Iterator ();
while (It.hasnext ()) {
String key;
String value;
Key=it.next (). toString ();
Value=map.get (key);
System.out.println (key+ "--" +value);
}

Using EntrySet () iteration
Java code

Iterator It=map.entryset (). Iterator ();
System.out.println (Map.entryset (). Size ());
String key;
String value;
while (It.hasnext ()) {
Map.entry Entry = (map.entry) it.next ();
Key=entry.getkey (). toString ();
Value=entry.getvalue (). toString ();
System.out.println (key+ "= = =" +value);
}

How Java Map traverses

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.