How to iterate over a map in Java

Source: Internet
Author: User

There are several ways of iterating overMapIn Java. Lets go over the most common methods and review their advantages and disadvantages. Since all maps in Java implementMapInterface,
Following techniques will work for any map implementation (HashMap,TreeMap,LinkedHashMap,Hashtable,
Etc .)

Method #1: iterating over entries using for-each loop.

This is the most common method and is preferable in most cases. shocould be used if you need both map keys and values in the loop.

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 that for-each loop was introduced in Java 5 so this method is working only in newer versions of the language. Also for-each loop will throwNullPointerExceptionIf you try to iterate over
A map that isnull, So before iterating you shoshould always checknullReferences.

Method #2: iterating over keys or values using for-each loop.

If you need only keys or values from the map, you can iterate overkeySetOrvaluesInsteadentrySet.

Map<Integer, Integer> map = new HashMap<Integer, Integer>();//iterating over keys onlyfor (Integer key : map.keySet()) {    System.out.println("Key = " + key);}//iterating over values onlyfor (Integer value : map.values()) {    System.out.println("Value = " + value);}

This method gives slight performance advantage overentrySetIteration (about 10% faster) and is more clean.

Method #3: iterating using Iterator.

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

Without 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 use same technique to iterate overkeySetOrvalues.

This method might look redundant but it has its own advantages. first of all it is the only way to iterate over a map in older versions of Java. the other important feature is that it is the only method that allows youRemoveEntries
From the map during iteration by callingiterator.remove(). If you try to do this during for-each iteration you will get "unpredictable results" according to javadoc.

From performance point of view this method is equal to for-each iteration.

Method #4: iterating over keys and searching for values (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);}

 

This might look like a cleaner alternative for method #1 but in practice it is pretty slow and inefficient as getting values by a key might be time consuming (this method in differentMapImplementations
Is 20%-200% slower than method #1). If you have findbugs installed, it will detect this and warn you about inefficient iteration. This method shoshould be avoided.

Conclusion

If you need only keys or values from the map use method #2. if you are stuck with older version of Java (less than 5) or planning to remove entries during iteration you have to use method #3. otherwise use method #1.

 

 

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.