Map and set Traversal (EntrySet method, supplementing enumeration and iterator)

Source: Internet
Author: User

 public  void   Mearge (map map) {map Returnmap  = new  Ha        Shmap<> ();  //  convert to Entry  set<map.entry        <object, object>> entries = Map.entryset ();  //  traverse  for  (map.entry<object, Object> Entry:entries) {Object key = Entry.getkey ();            Object val  = Entry.getvalue ();        System.out.println ( "key:value#" +key+ ":" +val "); }    }

The main use of the Map.entryset () method; Entry can be understood as a single key-value pair.

This also skips the process of set conversion to iterator and then traversal. Use foreach directly, in a concise manner.

Add a bit of knowledge about enumeration and iterator, before you see a blog post that says, use enumeration sparingly and use iterator more.

Enumeration interface main implementation of the two methods:

boolean hasMoreElements()Tests If this enumeration contains more elements.
E nextElement()Returns the next element of this enumeration if this enumeration object have at least one more element to provide.

boolean hasmoreelemerts (): Tests whether the enumeration enumeration object also contains elements, and if true, indicates that there are at least one element.
· Object Nextelement (): If the Bnumeration enumeration object also contains elements, the method gets the next element in the object.

Iterator interface Main method:

boolean hasNext()Returns true If the iteration have more elements.
E next()Returns the next element in the iteration.
void remove()Removes from the underlying collection The last element of returned by this iterator (optional operation).

As can be seen above, iterator more than enumeration a deletion method, the other two methods function is similar, so it is recommended to use the iterator interface.

Map and set Traversal (EntrySet method, supplementing enumeration and iterator)

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.