An efficient way to traverse a map: Map.entry and Map.entryset () _ Traverse Map

Source: Internet
Author: User
Tags map class

Have you ever felt tired of getting a keyword from a map and then getting the corresponding value? Using the Map.entry class, you can get all the information at the same time. The standard map access method is as follows:

Set keys = Map.keyset ();
if (keys!= null) {
iterator iterator = Keys.iterator ();
while (Iterator.hasnext ()) {
Object key = Iterator.next ();
Object value = Map.get (key);
; ....
;}

Then, there is a problem with this method. After getting the keyword from the map, it is tedious and time-consuming to return to the map each time to get a relative value.

Fortunately, there is a much simpler approach. The map class provides a method called EntrySet () that returns a map.entry set of objects that are instantiated. Next, the Map.entry class provides a Getkey () method and a GetValue () method, so the above code can be organized more logically. Examples are as follows:

Set entries = Map.entryset ();
if (entries!= null) {
iterator iterator = Entries.iterator ();
while (Iterator.hasnext ()) {
map.entry Entry =iterator.next ();
Object key = Entry.getkey ();
Object value = Entry.getvalue ();
; ....
}

Despite the addition of one line of code, we omit many "get" calls to map unnecessarily. At the same time, the developer is provided with a class that retains both the keyword and its corresponding value. Map.entry also provides a SetValue () method that programmers can use to modify values within a map.

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.