How to Iterate Over a Map in Java

There are several ways of iterating over a Map in Java. Lets go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement Mapinterface, following techniques will work for any map implementation (HashMapTreeMap,LinkedHashMapHashtable, etc.)

Method #1: Iterating over entries using For-Each loop.

This is the most common method and is preferable in most cases. Should 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 throw NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for null references.

        

Method #2: Iterating over keys or values using For-Each loop.

If you need only keys or values from the map, you can iterate over keySet or valuesinstead of entrySet.

Map<Integer, Integer> map = new HashMap<Integer, Integer>();

//iterating over keys only
for (Integer key : map.keySet()) {
    System.out.println("Key = " + key);
}

//iterating over values only
for (Integer value : map.values()) {
    System.out.println("Value = " + value);
}


         

This method gives slight performance advantage over entrySet iteration (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 over keySet or values.

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 you to remove entries 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 different Mapimplementations is 20%-200% slower than method #1). If you have FindBugs installed, it will detect this and warn you about inefficient iteration. This method should 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.

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值