4 ways to traverse Map objects in Java

How to traverse Map objects in Java

How to Iterate Over a Map in Java

There are many ways to traverse Map in java. Let's take a look at the most commonly used methods and their advantages and disadvantages.

Since all maps in java implement the Map interface, the following methods are applicable to any map implementation (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.)

 

Method 1: Use entries to traverse in a for-each loop

This is the most common and in most cases the most desirable way to traverse. Use when the key and value are needed.

[java]  view plain   copy
  1. Map<Integer, Integer> map = new HashMap<Integer, Integer>();  
  2.   
  3. for (Map.Entry<Integer, Integer> entry : map.entrySet()) {  
  4.   
  5.     System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
  6.   
  7. }  


Note: The for-each loop was introduced in Java  5 so this method can only be used in Java 5 or higher. If you are traversing an empty map object, the for-each loop will throw a NullPointerException, so you should always check for null references before traversing.

 

Method two traverse the keys or values ​​in the for-each loop.

If you only need the keys or values ​​in the map, you can traverse through keySet or values ​​instead of entrySet.

[java]  view plain   copy
  1. Map<Integer, Integer> map = new HashMap<Integer, Integer>();  
  2.   
  3. //Traverse the keys in the map  
  4.   
  5. for (Integer key : map.keySet()) {  
  6.   
  7.     System.out.println("Key = " + key);  
  8.   
  9. }  
  10.   
  11. //Traverse the values ​​in the map  
  12.   
  13. for (Integer value : map.values()) {  
  14.   
  15.     System.out.println("Value = " + value);  
  16.   
  17. }  


This method is slightly better in performance than entrySet traversal (10% faster), and the code is cleaner.

 

Method three uses Iterator to traverse

Use generics:

[java]  view plain   copy
  1. Map<Integer, Integer> map = new HashMap<Integer, Integer>();  
  2.   
  3. Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();  
  4.   
  5. while (entries.hasNext()) {  
  6.   
  7.     Map.Entry<Integer, Integer> entry = entries.next();  
  8.   
  9.     System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
  10.   
  11. }  


不使用泛型:

[java]  view plain   copy
  1. Map map = new HashMap();  
  2.   
  3. Iterator entries = map.entrySet().iterator();  
  4.   
  5. while (entries.hasNext()) {  
  6.   
  7.     Map.Entry entry = (Map.Entry) entries.next();  
  8.   
  9.     Integer key = (Integer)entry.getKey();  
  10.   
  11.     Integer value = (Integer)entry.getValue();  
  12.   
  13.     System.out.println("Key = " + key + ", Value = " + value);  
  14.   
  15. }  


你也可以在keySet和values上应用同样的方法。

该种方式看起来冗余却有其优点所在。首先,在老版本java中这是惟一遍历map的方式。另一个好处是,你可以在遍历时调用iterator.remove()来删除entries,另两个方法则不能。根据javadoc的说明,如果在for-each遍历中尝试使用此方法,结果是不可预测的。

从性能方面看,该方法类同于for-each遍历(即方法二)的性能。

 

方法四、通过键找值遍历(效率低)

[java]  view plain   copy
  1. Map<Integer, Integer> map = new HashMap<Integer, Integer>();  
  2.   
  3. for (Integer key : map.keySet()) {  
  4.   
  5.     Integer value = map.get(key);  
  6.   
  7.     System.out.println("Key = " + key + ", Value = " + value);  
  8.   
  9. }  


As an alternative to Method 1, this code looks cleaner; but in fact it is quite slow and inefficient. Because getting the value from the key is a time-consuming operation (compared to method 1, this method is 20%~200% slower in different Map implementations). If you install FindBugs, it will check and warn you about inefficient traversals. So try to avoid it.

 

to sum up

If you only need keys or values, use method two. If you are using a language version lower than Java 5, or if you plan to delete entries during traversal, you must use method 3. Otherwise, use method one (both key and value).

Guess you like

Origin blog.csdn.net/qq_36961530/article/details/71542948