How to traverse HashMap in Java

Source: Internet
Author: User

  One.

HASHMAP staff = new HashMap ();

Add keyword value pairs, write your own traversal

Set entries = Staff.entryset ();

Iterator iter = Entries.iterator ();

while (Iter.hasnext ())

{

Map.entry Entry = (map.entry) iter.next ();

Object key = Entry.getkey (); Key words

Object value = Entry.getvalue ();

}

  Two.

Map map = new HashMap ();

for (Iterator iter = Map.entryset (). iterator (); Iter.hasnext ();) {

Map.entry Entry = (map.entry) iter.next (); Map.entry to remove key values simultaneously

Object key = Entry.getkey ();

Object val = Entry.getvalue ();

}

  Three.

Map map = new HashMap ();

for (Iterator iter = Map.keyset (). iterator (); Iter.hasnext ();) {

Object key = Iter.next ();

Object val = map.get (key);

}

  Iterator is an iterator

For the keyset is actually traversed 2 times, one is to iterator, once from the HashMap out of the value of the key.

And EntrySet just traversed the first time, he put the key and value are placed in the entry, so fast.

For us to do the web, may not be part of the Vo object or form to encapsulate information, so when you use HashMap, it is stored in the above objects. Therefore, the use of EntrySet traversal performance will improve.

HashMap use a lot, such as importing information to use, because most of the imported information to determine whether there is duplicate information, so you can use ContainsKey to deal with, and do not have to do when inserting the processing.

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.