3532

What's the best way to iterate over the items in a HashMap?

S.S. Anne
  • 13,819
  • 7
  • 31
  • 62
burntsugar
  • 54,120
  • 21
  • 51
  • 77

7 Answers7

5033

If you're only interested in the keys, you can iterate through the keySet() of the map:

Map<String, Object> map = ...;

for (String key : map.keySet()) {
    // ...
}

If you only need the values, use values():

for (Object value : map.values()) {
    // ...
}

Finally, if you want both the key and value, use entrySet():

for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}

One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see karim79's answer). However, changing item values is OK (see Map.Entry).

Ihor Patsian
  • 1,258
  • 2
  • 15
  • 23
harto
  • 84,815
  • 7
  • 43
  • 60
  • 3
    So how to do loop through 2 maps simultaneously? using the entrySet method? I tried using && but it ddnt work – DaMainBoss Jul 26 '11 at 18:18
  • 2
    Use two iterators. See the accepted answer for example usage of an iterator. – harto Jul 27 '11 at 04:08
  • 21
    It's only more efficient to use entrySet when you need both keys and values. If you only need one or the other then just use that one: http://stackoverflow.com/questions/3870064/performance-considerations-for-keyset-and-entryset-of-map/6927754#6927754 – rogerdpack Oct 05 '11 at 23:14
  • 4
    One more important point, the Set returned by keySet() and Collection returned by values() are both backed by the original Map. That is, if you make any modification in them they will be reflected back in the Map, however, both of them don't support add() and addAll() methods i.e. you can't add new key to the Set or new value in the Collection. – sactiw Jan 24 '14 at 08:27
  • About getting both values and keys, it's not just simpler to use the first `foreach` example and get the value inside the loop, with `value = map.get(key)`? Is the performance of `entrySet` more high? – Marco Sulla Apr 18 '17 at 08:54
  • @MarcoSulla Performance questions like that depend, you should measure and see in cases that matter. It is likely that using `entrySet` is faster because it can avoid doing a lookup for every entry. The implementation of the particular `Map` determines which way is better and by how much. The GC pressure at that point could also be a factor. – doug65536 Aug 06 '17 at 22:05
  • Since map doesn't come under **Iterator** class how in the first solution the person has used iterator? – Rishabh Agarwal Dec 06 '17 at 06:44
  • I get and incompatible types error for 'Map.Entry entry' and 'Map.Entry entry: "required Object, found Entry". I'm mapping integers to hashmaps. Having to use the keyset for loop because of this and pull the value through 'value = (HashMap) integertomap.get(key)', though less efficient then if I could use entrySet without iterater as per your example. – Androidcoder Jul 25 '18 at 16:24
  • Best explanation thank you. – EM-Creations Jan 04 '21 at 13:45
  • What about adding values? – Heath Mitchell Mar 06 '21 at 12:27
3384

Iterate through the entrySet() like so:

public static void printMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
        it.remove(); // avoids a ConcurrentModificationException
    }
}

Read more about Map.

Neuron
  • 3,776
  • 3
  • 24
  • 44
karim79
  • 326,960
  • 63
  • 404
  • 402
  • 38
    Though old style, this will help avoid ConcurrentModificationExceptions over the new foreach style in the answers below. You can for instance remove via the seperate iterator. – Benjamin Wootton Dec 16 '10 at 09:22
  • 467
    @karim79 what do you think about the following way: `Map map = new HashMap(); for (Map.Entry entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }` – fresh_dev Oct 25 '11 at 08:56
  • 14
    by calling 'it.remove(); ' you are emptying the map making it not reusable if this map was a class variable. Do you have any solution to that? – vim Jan 10 '12 at 09:47
  • 27
    @vimukthi what do you mean a solution to that? Just remove the `it.remove();` line. – Danny Jan 26 '12 at 19:07
  • 114
    The for `(Map.Entry cursor : map.entrySet()) {...}` syntax is much better. – Chad Okere Jan 28 '12 at 17:29
  • 2
    Is there any difference on chances of ConcurrentModificationExceptions between both syntaxs in terms of calling remove() or not? Some answers imply contradictory assertions (first vs fourth comments) – Whimusical Jul 19 '12 at 12:41
  • 4
    Iterator interface is generic since 1.2. It need to be Iterator – etlds Mar 05 '13 at 19:37
  • I consider that the answer of arvnid, despite is just a copy/paste or not. (I agree that is ethical to give the proper credits to the one who belongs) – Victor Feb 28 '14 at 15:46
  • 7
    I landed up here accidentally, why did we do `Iterator.remove()` here? OP just asked for a best way for iterating over a `Map` – Puru-- Apr 13 '14 at 18:42
  • Note that it.remove will not work with unmodifiable Maps, like System.getenv() return String Map. – J E Carter II May 14 '14 at 15:06
  • The full type of iterator is : import java.util.Iterator; – Moebius Sep 03 '14 at 13:13
  • 2
    @harto's answer is a better one as it tells the reader how to actually use this in a variety of cases. Your solution's application range is tiny. Very tiny. – Hele Dec 15 '14 at 05:19
  • Don't you jump over the first entry using the "linewhile (it.hasNext())"? – Jürgen K. Oct 19 '15 at 17:38
  • So the big picture steps seem to be 1. convert to a set using entrySet 2. turn it into an iterator and 3. call hasNext and turn each next Object into a Map.Entry Object? – Jwan622 Jan 07 '16 at 16:03
  • 4
    Everyone saying that `for (Map.Entry cursor : map.entrySet())` is better than this is ignoring the fact that you will still receive a `ConcurrentModificationException` using that method. The selected answer remains the best method to iterate through a `Map`. – ashishduh Dec 02 '16 at 18:22
  • @JürgenK. No, `it.hasNext()` returns a boolean based on whether the iterator has another element beyond the current one but does not advance the iterator's state. The iterator isn't advanced to the next element until `it.next()` is called. – apraetor May 11 '17 at 22:00
  • @Alex yeah me too – NimChimpsky May 31 '17 at 02:37
  • 1
    @ashishduh The selected answer is only the best in the *special case* where you need to modify the map during iteration. For all other uses, using an enhanced for loop is preferable. – nemetroid Jun 29 '17 at 08:22
  • This API is not intuitive, so I google this answer repeatedly and was at least 20 times on this answer!! – phil Jul 06 '17 at 13:49
  • @etlds Actually, Java 1.2 introduced Iterator, but didn't have generics back then. Generics were only added in 1.5. – Paŭlo Ebermann Aug 21 '17 at 17:57
  • 1
    Please do not use Iterator anymore. – Impulse The Fox Sep 18 '17 at 07:52
  • i get unchecked cast and unchecked assignment warnings for '(Map.Entry)it.next()'. I did add a check to Map,Entry: 'Map.Entry entry' to avoid other issues. – Androidcoder Oct 22 '17 at 21:56
  • Since _Map_ is not under **Iterator** class, _how can you use iterator with map ?_ Only List, Queue and Set are iterable. – Rishabh Agarwal Dec 06 '17 at 06:45
  • Perhaps update this for Java 8? (E.g. providing two versions, one for before Java 8 and one that only works on Java 8.) – Peter Mortensen Feb 06 '18 at 22:57
  • ConcurrentHashMap is an implementation of ConcurrentMap interface. ConcurrentMap Interface extends Map Interface. The confusion is because the question specifically asked for HashMap. HashMap is an implementation of Map interface. It is always better to declare a ConcurrentHashMap like: Map myMap = new ConcurrentHashMap(); instead of : ConcurrentHashMap myMap = new ConcurrentHashMap(); This first practice allows extensibility. That is the reason this is a mature answer. – technazi Apr 19 '18 at 04:06
  • 1
    I consider it bad answer. OP was asking just for iterating over map, not how to modify map during iteration. – Mader Levap Mar 01 '19 at 13:05
  • 1
    @MaderLevap I disagree. He's showing the safest way of iterating over a map. The remove(); is an example of something that could cause exceptions on other types of lists/collections that would be avoided using this method. – CAM_344 Apr 27 '20 at 15:12
  • import java.util.*; class MapToList { public static void main(String args[]){ Map map = new HashMap(); map.put(1,"Rohit"); map.put(2,"Rahul"); map.put(3,"Mohit"); Iterator itr = map.entrySet().iterator(); while(itr.hasNext()) { Map.Entry it = (Map.Entry)itr.next(); System.out.println("Printing map" + it.getKey() + it.getValue()) ; } } } – Rohit Chaurasiya Dec 06 '20 at 19:50
852

Extracted from the reference How to Iterate Over a Map in Java:

There are several ways of iterating over a Map in Java. Let's go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement the Map interface, the following techniques will work for any map implementation (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.)

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

This is the most common method and is preferable in most cases. It 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 the For-Each loop was introduced in Java 5, so this method is working only in newer versions of the language. Also a 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 a For-Each loop.

If you need only keys or values from the map, you can iterate over keySet or values instead 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 a 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 calling iterator.remove(). If you try to do this during For-Each iteration you will get "unpredictable results" according to Javadoc.

From a performance point of view this method is equal to a 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 Map implementations 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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
arvind
  • 8,575
  • 1
  • 11
  • 5
  • 1
    Lets add the small caevet, that in case of `ConcurrentMap`s, iteration on `keySet()` will crash in general (there is no guarantee the values exist for earlier-gathered keys). On the other hand using iterators or entries is safe (they always refer to existing objects). – P Marecki Feb 29 '16 at 12:34
  • 2
    @arvind How would method #4 ever be inefficient? By definition, calling `get()` is always O(1) for a HashMap. That is the definition of a HashMap and the user asked for a HashMap. I do not get why this is so highly upvoted. If you are going to reference someone else's link, make sure it actually makes sense for the question asked. – ohbrobig Jun 03 '18 at 13:09
  • 1
    @ohbrobig yet it's O(1) but that's the runtime, that's how it scale. It doesn't mean it will necessarily get the value in the first cycle.Method#4 will definitely be slower then Method#1 – user961954 Apr 13 '19 at 08:45
176
for (Map.Entry<String, String> item : hashMap.entrySet()) {
    String key = item.getKey();
    String value = item.getValue();
}
c-an
  • 2,036
  • 1
  • 17
  • 46
gabor
  • 3,953
  • 5
  • 20
  • 20
104

You can iterate through the entries in a Map in several ways. Get each key and value like this:

Map<?,?> map = new HashMap<Object, Object>();
for(Entry<?, ?> e: map.entrySet()){
    System.out.println("Key " + e.getKey());
    System.out.println("Value " + e.getValue());
}

Or you can get the list of keys with

Collection<?> keys = map.keySet();
for(Object key: keys){
    System.out.println("Key " + key);
    System.out.println("Value " + map.get(key));
}

If you just want to get all of the values and aren't concerned with the keys, you can use:

Collection<?> values = map.values();
Neuron
  • 3,776
  • 3
  • 24
  • 44
codethulhu
  • 3,786
  • 1
  • 18
  • 15
72

Smarter:

for (String key : hashMap.keySet()) {
    System.out.println("Key: " + key + ", Value: " + map.get(key));
}
jkarretero
  • 931
  • 6
  • 2
  • 9
    this actually depends on whether or not you need the keys. if not, it's more efficient to use entrySet() as hashCode() does not get called. – icfantv Oct 05 '11 at 22:33
  • 15
    map.get(key) for every iteration is not smarter -- its way slower – CompEng88 Apr 18 '13 at 21:30
  • 2
    map.entrySet() which returns entries which already contains both the key and the value. This way you don't have to call hashCode() and search the hash during the iteration. – CompEng88 Apr 16 '16 at 13:11
  • Java 8 syntax. May still not work for Android development. "Android is not intended to be 100% compatible with any Java SE API version, not 6 nor 8 nor any. ... The JRE is the Java Runtime Environment while the JDK is the Java Development Kit. It is the JDK that you need for Android application development along with the existing Android SDK.Dec 9, 2013" [source](https://stackoverflow.com/questions/20480090/does-android-support-jdk-6-or-7) – jasonleonhard Aug 05 '17 at 22:40
51

Depends. If you know you're going to need both the key and the value of every entry, then go through the entrySet. If you just need the values, then there's the values() method. And if you just need the keys, then use keyset().

A bad practice would be to iterate through all of the keys, and then within the loop, always do map.get(key) to get the value. If you're doing that, then the first option I wrote is for you.

bofredo
  • 2,310
  • 6
  • 30
  • 49
Gary Kephart
  • 4,540
  • 5
  • 38
  • 50
  • 1
    One more important point, the Set returned by keySet() and Collection returned by values() are both backed by the original Map. That is, if you make any modification in them they will be reflected back in the Map, however, both of them don't support add() and addAll() methods i.e. you can't add new key to the Set or new value in the Collection. – sactiw Jan 24 '14 at 08:25