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.
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.
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:
不使用泛型:
你也可以在keySet和values上应用同样的方法。
该种方式看起来冗余却有其优点所在。首先,在老版本java中这是惟一遍历map的方式。另一个好处是,你可以在遍历时调用iterator.remove()来删除entries,另两个方法则不能。根据javadoc的说明,如果在for-each遍历中尝试使用此方法,结果是不可预测的。
从性能方面看,该方法类同于for-each遍历(即方法二)的性能。
方法四、通过键找值遍历(效率低)
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).