Java traversal HashMap, HashSet, Hashtable

Source: Internet
Author: User

I. Traversing HASHMAP

Map<integer, string> map = new Hashmap<integer, string> ();

Method One: High efficiency

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

Method Two:

For (Integer Key:map.keySet ()) {
String value = Map.get (key); (This will result in inefficient, not recommended.) )
System.out.println (value);
}

You can also traverse the value individually

For (Integer value:map.values ()) {
System.out.println ("value =" + value);
}

Method Three: (benefit: Can be called iterator.remove () to delete entries)

Iterator<map.entry<integer, integer>> entries = Map.entryset (). Iterator ();
while (Entries.hasnext ()) {
Map.entry<integer, integer> Entry = Entries.next ();
System.out.println ("Key =" + entry.getkey () + ", Value =" + Entry.getvalue ());
}

Two. Traverse HashSet

Set set = new HashSet ();

For (Iterator it=set.iterator (); It.hasnext ();) {
System.out.println (It.next ());
}

Three. Traverse Hashtable (synchronous, thread-safe)

Hashtable table = new Hashtable ();

Traverse key
Enumeration E = Table.keys ();

while (E. hasmoreelements ()) {

System.out.println (E.nextelement ());

}
Traverse value
E = Table.elements ();

while (E. hasmoreelements ()) {

System.out.println (E.nextelement ());

}

Java traversal HashMap, HashSet, Hashtable

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.