How to traverse HashMap in Java

Source: Internet
Author: User


The first is the use of the HashMap EntrySet () method:
 
     map<string,string> map = new hashmap<string,string> ();   Iterator iter = Map.entryset (). Iterator ();   while (Iter.hasnext ()) {Map.entry Entry = (map.entry) iter.next ();   String key = Entry.getkey ();   String val = Entry.getvalue (); }

  


The second is to use HashMap's keyset () method:
  
     map<string,string> map = new hashmap<string,string> ();   Iterator iter = Map.keyset (). Iterator ();   while (Iter.hasnext ()) {String key = Iter.next ();   String val = map.get (key); }

  

In both ways, the efficiency of the former is higher than that of the latter, mainly because the former actually puts both the key and the value into the iterator, and only executes once to find all the key-value pairs. and the latter equivalent to execute two times, the first time the key and value are deposited into the iterator, the second time from the HashMap

Removing the value corresponding to key is equivalent to traversing the map again.




Is the first kind of good, simple ...

How to traverse HashMap in Java

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.