Several methods of traversing map and comparison of their advantages and disadvantages

Source: Internet
Author: User

public static void Main (string[] args) {


map<string, string> map = new hashmap<string, string> ();
Map.put ("1", "value1");
Map.put ("2", "value2");
Map.put ("3", "Value3");

The first: universal use, two times the value of
System.out.println ("Traverse key and value by Map.keyset:");
For (String Key:map.keySet ()) {
System.out.println ("key=" + key + "and value=" + map.get (key));
}

Second Kind
System.out.println ("Use iterator to traverse key and value via Map.entryset");
Iterator<map.entry<string, string>> it = Map.entryset (). iterator ();
while (It.hasnext ()) {
map.entry<string, string> Entry = It.next ();
System.out.println ("key=" + entry.getkey () + "and value=" + entry.getvalue ());
}

Third: recommended, especially when the capacity is large
System.out.println ("Traverse key and value via Map.entryset");
For (map.entry<string, string> entry:map.entrySet ()) {
System.out.println ("key=" + entry.getkey () + "and value=" + entry.getvalue ());
}

Fourth Kind
System.out.println ("Traverse all value through Map.values (), but cannot traverse key");
For (String v:map.values ()) {
System.out.println ("value=" + V);
}
}

There are many ways to traverse a map in Java. Let's look at the most common methods and their pros and cons.


Since all maps in Java implement the map interface, the following methods apply to any map implementation (HASHMAP, TreeMap, Linkedhashmap, Hashtable, etc.)





Method one uses entries in the For-each loop to traverse the


This is the most common and, in most cases, the most desirable way to traverse. Used when the key values are required.


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


For (Map.entry<integer, integer> entry:map.entrySet ()) {


System.out.println ("Key =" + entry.getkey () + ", Value =" + Entry.getvalue ());


}


Note: The For-each loop is introduced in Java 5 so this method can only be applied to Java 5 or later. If you traverse an empty map object, the For-each loop throws NullPointerException, so you should always check for null references before traversing.





Method Two traverses the keys or values in the For-each loop.


If you only need a key or value in a map, you can traverse it by keyset or values instead of using EntrySet.


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


Traversing the keys in the map


For (Integer Key:map.keySet ()) {


System.out.println ("key =" + key);


}





Traversing values in a map


For (Integer value:map.values ()) {


System.out.println ("value =" + value);


}


This method is slightly better than the EntrySet traversal (Fast 10%), and the code is cleaner.





Method three uses iterator traversal


Use generics:


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


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 ());


}


Do not use generics:


Map map = new HashMap ();


Iterator entries = Map.entryset (). iterator ();


while (Entries.hasnext ()) {


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


Integer key = (integer) entry.getkey ();


Integer value = (integer) entry.getvalue ();


System.out.println ("key =" + key + ", value =" + value);


}


You can also apply the same method in keyset and values.


This approach looks redundant but has its advantages. First, this is the only way to traverse a map in the old version of Java. Another advantage is that you can call Iterator.remove () over the duration to delete the entries, and the other two methods cannot. According to Javadoc's instructions, if you try this method in For-each traversal, the results are unpredictable.


In terms of performance, this method is similar to the performance of For-each traversal (i.e. Method II).





Method Four, through the key to find value traversal (inefficient)


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


For (Integer Key:map.keySet ()) {


Integer value = Map.get (key);


System.out.println ("key =" + key + ", value =" + value);


}


As an alternative to method one, the code looks cleaner, but in fact it is rather slow and inefficient. Because the value from the key is a time-consuming operation (compared with method one, the method is slow 20%~200% in different map implementations). If you install FindBugs, it will check and warn you about which is inefficient traversal. So try to avoid using it.





Summarize


Use method Two if only the key (keys) or value (values) are required.


If you are using a language version below Java 5, or if you intend to delete entries over the duration, you must use method three.


Otherwise, use method one (the key values are all).


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.