By iMack


2008-09-05 21:12:48 8 Comments

If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?

Will the ordering of elements depend on the specific map implementation that I have for the interface?

30 comments

@Basil Bourque 2019-10-26 19:44:57

If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?

If efficiency of looping the keys is a priority for your app, then choose a Map implementation that maintains the keys in your desired order.

Will the ordering of elements depend on the specific map implementation that I have for the interface?

Yes, absolutely.

  • Some Map implementations promise a certain iteration order, others do not.
  • Different implementations of Map maintain different ordering of the key-value pairs.

See this table I created summarizing the various Map implementations bundled with Java 11. Specifically, notice the iteration order column. Click/tap to zoom.

A table describing aspects of the various <code>Map</code> implementations bundled with Java 11.

You can see there are four that maintain an interaction order. Two of those implement the NavigableMap interface.

The older SortedMap interface is effectively supplanted by the newer NavigableMap interface. But you may find 3rd-party implementations implementing the older interface only.

Natural order

If you want a Map that keeps its pairs arranged by the “natural order” of the key, use TreeMap or ConcurrentSkipListMap. The term “natural order” means the class of the keys implements Comparable. The value returned by the compareTo method is used for comparison in sorting.

Custom order

If you want to specify a custom sorting routine for your keys to be used in maintaining a sorted order, pass a Comparator implementation appropriate to the class of your keys. Use either TreeMap or ConcurrentSkipListMap, passing your Comparator.

Original insertion order

If you want the pairs of your map to be kept in their original order in which you inserted them into the map, use LinkedHashMap.

Enum-definition order

If you are using an enum such as DayOfWeek or Month as your keys, use the EnumMap class. Not only is this class highly optimized to use very little memory and run very fast, it maintains your pairs in the order defined by the enum. For DayOfWeek, for example, the key of DayOfWeek.MONDAY will be first found when iterated, and the key of DayOfWeek.SUNDAY will be last.

@Shivam Agrawal 2017-11-05 14:18:17

Iterating a Map is very easy.

for(Object key: map.keySet()){
   Object value= map.get(key);
   //Do your stuff
}

For instance, you have a Map<String, int> data;

for(Object key: data.keySet()){
  int value= data.get(key);
}

@michaeak 2018-12-12 12:00:47

Well, this is unnecessarily slow because first get the keys and then the entries. Alternative: Get the entrySets and then for each entryset the key and the value

@Viacheslav Vedenin 2016-02-22 16:37:29

To summarize the other answers and combine them with what I know, I found 10 main ways to do this (see below). Also, I wrote some performance tests (see results below). For example, if we want to find the sum of all of the keys and values of a map, we can write:

  1. Using iterator and Map.Entry

    long i = 0;
    Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<Integer, Integer> pair = it.next();
        i += pair.getKey() + pair.getValue();
    }
    
  2. Using foreach and Map.Entry

    long i = 0;
    for (Map.Entry<Integer, Integer> pair : map.entrySet()) {
        i += pair.getKey() + pair.getValue();
    }
    
  3. Using forEach from Java 8

    final long[] i = {0};
    map.forEach((k, v) -> i[0] += k + v);
    
  4. Using keySet and foreach

    long i = 0;
    for (Integer key : map.keySet()) {
        i += key + map.get(key);
    }
    
  5. Using keySet and iterator

    long i = 0;
    Iterator<Integer> itr2 = map.keySet().iterator();
    while (itr2.hasNext()) {
        Integer key = itr2.next();
        i += key + map.get(key);
    }
    
  6. Using for and Map.Entry

    long i = 0;
    for (Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); entries.hasNext(); ) {
        Map.Entry<Integer, Integer> entry = entries.next();
        i += entry.getKey() + entry.getValue();
    }
    
  7. Using the Java 8 Stream API

    final long[] i = {0};
    map.entrySet().stream().forEach(e -> i[0] += e.getKey() + e.getValue());
    
  8. Using the Java 8 Stream API parallel

    final long[] i = {0};
    map.entrySet().stream().parallel().forEach(e -> i[0] += e.getKey() + e.getValue());
    
  9. Using IterableMap of Apache Collections

    long i = 0;
    MapIterator<Integer, Integer> it = iterableMap.mapIterator();
    while (it.hasNext()) {
        i += it.next() + it.getValue();
    }
    
  10. Using MutableMap of Eclipse (CS) collections

    final long[] i = {0};
    mutableMap.forEachKeyValue((key, value) -> {
        i[0] += key + value;
    });
    

Perfomance tests (mode = AverageTime, system = Windows 8.1 64-bit, Intel i7-4790 3.60 GHz, 16 GB)

  1. For a small map (100 elements), score 0.308 is the best

    Benchmark                          Mode  Cnt  Score    Error  Units
    test3_UsingForEachAndJava8         avgt  10   0.308 ±  0.021  µs/op
    test10_UsingEclipseMap             avgt  10   0.309 ±  0.009  µs/op
    test1_UsingWhileAndMapEntry        avgt  10   0.380 ±  0.014  µs/op
    test6_UsingForAndIterator          avgt  10   0.387 ±  0.016  µs/op
    test2_UsingForEachAndMapEntry      avgt  10   0.391 ±  0.023  µs/op
    test7_UsingJava8StreamApi          avgt  10   0.510 ±  0.014  µs/op
    test9_UsingApacheIterableMap       avgt  10   0.524 ±  0.008  µs/op
    test4_UsingKeySetAndForEach        avgt  10   0.816 ±  0.026  µs/op
    test5_UsingKeySetAndIterator       avgt  10   0.863 ±  0.025  µs/op
    test8_UsingJava8StreamApiParallel  avgt  10   5.552 ±  0.185  µs/op
    
  2. For a map with 10000 elements, score 37.606 is the best

    Benchmark                           Mode   Cnt  Score      Error   Units
    test10_UsingEclipseMap              avgt   10    37.606 ±   0.790  µs/op
    test3_UsingForEachAndJava8          avgt   10    50.368 ±   0.887  µs/op
    test6_UsingForAndIterator           avgt   10    50.332 ±   0.507  µs/op
    test2_UsingForEachAndMapEntry       avgt   10    51.406 ±   1.032  µs/op
    test1_UsingWhileAndMapEntry         avgt   10    52.538 ±   2.431  µs/op
    test7_UsingJava8StreamApi           avgt   10    54.464 ±   0.712  µs/op
    test4_UsingKeySetAndForEach         avgt   10    79.016 ±  25.345  µs/op
    test5_UsingKeySetAndIterator        avgt   10    91.105 ±  10.220  µs/op
    test8_UsingJava8StreamApiParallel   avgt   10   112.511 ±   0.365  µs/op
    test9_UsingApacheIterableMap        avgt   10   125.714 ±   1.935  µs/op
    
  3. For a map with 100000 elements, score 1184.767 is the best

    Benchmark                          Mode   Cnt  Score        Error    Units
    test1_UsingWhileAndMapEntry        avgt   10   1184.767 ±   332.968  µs/op
    test10_UsingEclipseMap             avgt   10   1191.735 ±   304.273  µs/op
    test2_UsingForEachAndMapEntry      avgt   10   1205.815 ±   366.043  µs/op
    test6_UsingForAndIterator          avgt   10   1206.873 ±   367.272  µs/op
    test8_UsingJava8StreamApiParallel  avgt   10   1485.895 ±   233.143  µs/op
    test5_UsingKeySetAndIterator       avgt   10   1540.281 ±   357.497  µs/op
    test4_UsingKeySetAndForEach        avgt   10   1593.342 ±   294.417  µs/op
    test3_UsingForEachAndJava8         avgt   10   1666.296 ±   126.443  µs/op
    test7_UsingJava8StreamApi          avgt   10   1706.676 ±   436.867  µs/op
    test9_UsingApacheIterableMap       avgt   10   3289.866 ±  1445.564  µs/op
    

Graphs (performance tests depending on map size)

Enter image description here

Table (perfomance tests depending on map size)

          100     600      1100     1600     2100
test10    0.333    1.631    2.752    5.937    8.024
test3     0.309    1.971    4.147    8.147   10.473
test6     0.372    2.190    4.470    8.322   10.531
test1     0.405    2.237    4.616    8.645   10.707
test2     0.376    2.267    4.809    8.403   10.910
test7     0.473    2.448    5.668    9.790   12.125
test9     0.565    2.830    5.952   13.220   16.965
test4     0.808    5.012    8.813   13.939   17.407
test5     0.810    5.104    8.533   14.064   17.422
test8     5.173   12.499   17.351   24.671   30.403

All tests are on GitHub.

@GPI 2016-05-12 11:53:34

@Viacheslav : very nice answer. Just wondering how Java8 apis are hindered, in your benchmark, by capturing lambdas... (e.g. long sum = 0; map.forEach( /* accumulate in variable sum*/); captures the sum long, which may be slower than say stream.mapToInt(/*whatever*/).sum for example. Of course you can not always avoid capturing state, but that may be a reasonnable addition to the bench.

@talex 2016-09-13 15:20:53

Your 8 test is wrong. it access same variable from different threads without synchronization. Change to AtomicInteger to solve problem.

@ZhekaKozlov 2017-03-16 18:27:49

Why is Java 8 forEach slower on 100000 elements while it was the fastest on 100 and 10000?

@Holger 2017-03-17 18:28:28

@ZhekaKozlov: look at the mindblowingly large error values. Consider that a test result of x±e implies that there were result within the interval from x-e to x+e, so the fastest result (1184.767±332.968) ranges from 852 to 1518, whereas the second slowest (1706.676±436.867) runs between 1270 and 2144, so the results still overlap significantly. Now look at the slowest result, 3289.866±1445.564, which implies diverging between 1844 and 4735 and you know that these test results are meaningless.

@glglgl 2017-06-04 21:45:15

What about map.entrySet().stream().[parallel().]mapToInt(e -> e.getKey() + e.getValue()).sum();?

@Thierry 2017-11-07 23:37:57

What about comparing the 3 main implementations : HashMap, LinkedHashMap and TreeMap ?

@ErikE 2018-07-14 19:04:12

#1 and #6 are exactly the same. Using while vs. a for loop is not a different technique for iterating. And I am surprised they have such variation between them in your tests—which suggests that the tests are not properly isolated from external factors unrelated to the things you intend to be testing.

@njzk2 2018-12-10 05:01:40

for #7, use map + reduce, not forEach.

@Todd Sewell 2019-01-02 13:00:27

#8 is a terrible example, because of the parallel there's now a race condition when adding to i.

@Sina Madani 2019-02-26 19:32:26

You don't need .stream() to for forEach since it's also defined on the Iterable interface.

@Lova Chittumuri 2019-08-02 07:30:38

Using Java 7

Map<String,String> sampleMap = new HashMap<>();
for (sampleMap.Entry<String,String> entry : sampleMap.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();

    /* your Code as per the Business Justification  */

}

Using Java 8

Map<String,String> sampleMap = new HashMap<>();

sampleMap.forEach((k, v) -> System.out.println("Key is :  " + k + " Value is :  " + v));

@user1098063 2019-06-05 19:56:47

I like to concat a counter, then save the final value of the counter;

int counter = 0;
HashMap<String, String> m = new HashMap<String, String>();
for(int i = 0;i<items.length;i++)
{
m.put("firstname"+i, items.get(i).getFirstName());
counter = i;
}

m.put("recordCount",String.valueOf(counter));

Then when you want to retrieve:

int recordCount = Integer.parseInf(m.get("recordCount"));
for(int i =0 ;i<recordCount;i++)
{
System.out.println("First Name :" + m.get("firstname"+i));
}

@Nitin Mahesh 2015-10-06 15:07:33

Lambda Expression Java 8

In Java 1.8 (Java 8) this has become lot easier by using forEach method from Aggregate operations(Stream operations) that looks similar to iterators from Iterable Interface.

Just copy paste below statement to your code and rename the HashMap variable from hm to your HashMap variable to print out key-value pair.

HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
/*
 *     Logic to put the Key,Value pair in your HashMap hm
 */

// Print the key value pair in one line.

hm.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));

// Just copy and paste above line to your code.

Below is the sample code that I tried using Lambda Expression. This stuff is so cool. Must try.

HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
    Random rand = new Random(47);
    int i = 0;
    while(i < 5) {
        i++;
        int key = rand.nextInt(20);
        int value = rand.nextInt(50);
        System.out.println("Inserting key: " + key + " Value: " + value);
        Integer imap = hm.put(key, value);
        if( imap == null) {
            System.out.println("Inserted");
        } else {
            System.out.println("Replaced with " + imap);
        }               
    }

    hm.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));

Output:

Inserting key: 18 Value: 5
Inserted
Inserting key: 13 Value: 11
Inserted
Inserting key: 1 Value: 29
Inserted
Inserting key: 8 Value: 0
Inserted
Inserting key: 2 Value: 7
Inserted
key: 1 value:29
key: 18 value:5
key: 2 value:7
key: 8 value:0
key: 13 value:11

Also one can use Spliterator for the same.

Spliterator sit = hm.entrySet().spliterator();

UPDATE


Including documentation links to Oracle Docs. For more on Lambda go to this link and must read Aggregate Operations and for Spliterator go to this link.

@i_am_zero 2015-09-02 01:00:00

Java 8

We have got forEach method that accepts a lambda expression. We have also got stream APIs. Consider a map:

Map<String,String> sample = new HashMap<>();
sample.put("A","Apple");
sample.put("B", "Ball");

Iterate over keys:

sample.keySet().forEach((k) -> System.out.println(k));

Iterate over values:

sample.values().forEach((v) -> System.out.println(v));

Iterate over entries (Using forEach and Streams):

sample.forEach((k,v) -> System.out.println(k + ":" + v)); 
sample.entrySet().stream().forEach((entry) -> {
            Object currentKey = entry.getKey();
            Object currentValue = entry.getValue();
            System.out.println(currentKey + ":" + currentValue);
        });

The advantage with streams is they can be parallelized easily in case we want to. We simply need to use parallelStream() in place of stream() above.

forEachOrdered vs forEach with streams ? The forEach does not follow encounter order (if defined) and is inherently non-deterministic in nature where as the forEachOrdered does. So forEach does not guarantee that the order would be kept. Also check this for more.

@ScArcher2 2008-09-05 21:15:52

Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}

@ScArcher2 2010-03-22 13:30:04

If you do that, then it won't work as Entry is a nested Class in Map. java.sun.com/javase/6/docs/api/java/util/Map.html

@jjujuma 2010-04-30 10:34:19

you can write the import as "import java.util.Map.Entry;" and it will work.

@Pureferret 2012-10-05 15:42:48

Would this work with an iterator?

@assylias 2012-10-08 10:34:14

@Pureferret The only reason you might want to use an iterator is if you need to call its remove method. If that is the case, this other answer shows you how to do it. Otherwise, the enhanced loop as shown in the answer above is the way to go.

@Josiah Yoder 2014-12-04 20:31:27

I believe the form Map.Entry is clearer than importing the inner class into the current namespace.

@Saras Arya 2015-04-06 11:19:11

where is map from map.entrySet() declared ?

@Fallenreaper 2015-06-22 13:10:51

quick Question: do the Generic values <String, String> need to match that of the Map? For Example, mine is <String, Foo>.

@intcreator 2015-09-28 20:28:07

This is assuming your Map is named map of course. Beginners might not catch on.

@jpaugh 2016-01-26 20:38:44

@brandaemon Agreed. Even for intermediates, it's nice to see precisely which type implements the entrySet method.

@dguay 2016-10-12 21:03:58

Note that you can use map.values() or map.keySet() if you want to loop through values or keys only.

@Marcus MacWilliam 2018-02-13 15:15:27

That is not efficient. The Map holds the data in an entry set. For speed always iterate over the entry set.

@Androidcoder 2018-07-25 16:44:31

I get and incompatible types error for 'Map.Entry entry' and 'Map.Entry<Integer,HashMap> 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.

@JimmyB 2018-11-14 14:09:21

@MarcusMacWilliam "The Map holds the data in an entry set" - This is not true for many Map implementations. See TreeMap implementation for example which traverses the tree for either keys, values or entries.

@user207421 2019-02-14 09:43:52

@ScArcher2 No it isn't. It is a nested interface, and even if it was a nested c,ass it would still work. This code works. Been using. It for 15 years. No import required.

@anandchaugule 2018-11-27 10:24:47

An effective iterative solution over a Map is a 'for each' loop from Java 5 through Java 7. Here it is:

for (String key : phnMap.keySet()) {
    System.out.println("Key: " + key + " Value: " + phnMap.get(key));
}

From Java 8 you can use a lambda expression to iterate over a Map. It is an enhanced 'forEach'

phnMap.forEach((k,v) -> System.out.println("Key: " + k + " Value: " + v));

If you want to write a conditional for lambda you can write it like this:

phnMap.forEach((k,v)->{
    System.out.println("Key: " + k + " Value: " + v);
    if("abc".equals(k)){
        System.out.println("Hello abc");
    }
});

@J.B.Vala 2014-01-03 12:28:28

There are several ways to iterate a map. Please refer to the following code.

When you iterate a map using iterator Interface you must go with Entry<K,V> or entrySet()

It looks like this:

import java.util.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class IteratMapDemo{

    public static void main(String arg[]){
        Map<String, String> mapOne = new HashMap<String, String>();
        mapOne.put("1", "January");
        mapOne.put("2", "February");
        mapOne.put("3", "March");
        mapOne.put("4", "April");
        mapOne.put("5", "May");
        mapOne.put("6", "June");
        mapOne.put("7", "July");
        mapOne.put("8", "August");
        mapOne.put("9", "September");
        mapOne.put("10", "Octomber");
        mapOne.put("11", "November");
        mapOne.put("12", "December");

        Iterator it = mapOne.entrySet().iterator();
        while(it.hasNext())
        {
            Map.Entry me = (Map.Entry) it.next();
            //System.out.println("Get Key through While loop = " + me.getKey());
        }
        for(Map.Entry<String, String> entry:mapOne.entrySet()){
            //System.out.println(entry.getKey() + "=" + entry.getValue());
        }

        for (Object key : mapOne.keySet()) {
            System.out.println("Key: " + key.toString() + " Value: " +
                               mapOne.get(key));
        }
    }
}

@Donald Raab 2012-12-18 23:13:13

With Eclipse Collections (formerly GS Collections), you would use the forEachKeyValue method on the MapIterable interface, which is inherited by the MutableMap and ImmutableMap interfaces and their implementations.

final MutableBag<String> result = Bags.mutable.empty();
MutableMap<Integer, String> map = Maps.mutable.of(1, "One", 2, "Two", 3, "Three");
map.forEachKeyValue(new Procedure2<Integer, String>()
{
    public void value(Integer key, String value)
    {
        result.add(key + value);
    }
});
Assert.assertEquals(Bags.mutable.of("1One", "2Two", "3Three"), result);

With Java 8 lambda syntax, you can write the code as follows:

MutableBag<String> result = Bags.mutable.empty();
MutableMap<Integer, String> map = Maps.mutable.of(1, "One", 2, "Two", 3, "Three");
map.forEachKeyValue((key, value) -> result.add(key + value));
Assert.assertEquals(Bags.mutable.of("1One", "2Two", "3Three"), result);

Note: I am a committer for Eclipse Collections.

@Taras Melnyk 2018-05-03 11:25:07

With Java 8

map.forEach((k, v) -> System.out.println((k + ":" + v)));

@bluehallu 2018-04-19 12:32:20

Most compact with Java 8:

map.entrySet().forEach(System.out::println);

@ABHAY JOHRI 2018-04-17 18:46:05

Use Java 8:

map.entrySet().forEach(entry -> System.out.println(entry.getValue()));

@Oleksandr Pyrohov 2018-04-17 19:06:39

There are already multiple answers with the same suggestion.

@Witold Kaczurba 2016-10-26 10:56:58

The ordering will always depend on the specific map implementation. Using Java 8 you can use either of these:

map.forEach((k,v) -> { System.out.println(k + ":" + v); });

Or:

map.entrySet().forEach((e) -> {
            System.out.println(e.getKey() + " : " + e.getValue());
        });

The result will be the same (same order). The entrySet backed by the map so you are getting the same order. The second one is handy as it allows you to use lambdas, e.g. if you want only to print only Integer objects that are greater than 5:

map.entrySet()
    .stream()
    .filter(e-> e.getValue() > 5)
    .forEach(System.out::println);

The code below shows iteration through LinkedHashMap and normal HashMap (example). You will see difference in the order:

public class HMIteration {


    public static void main(String[] args) {
        Map<Object, Object> linkedHashMap = new LinkedHashMap<>();
        Map<Object, Object> hashMap = new HashMap<>();

        for (int i=10; i>=0; i--) {
            linkedHashMap.put(i, i);
            hashMap.put(i, i);
        }

        System.out.println("LinkedHashMap (1): ");
        linkedHashMap.forEach((k,v) -> { System.out.print(k + " (#="+k.hashCode() + "):" + v + ", "); });

        System.out.println("\nLinkedHashMap (2): ");

        linkedHashMap.entrySet().forEach((e) -> {
            System.out.print(e.getKey() + " : " + e.getValue() + ", ");
        });


        System.out.println("\n\nHashMap (1): ");
        hashMap.forEach((k,v) -> { System.out.print(k + " (#:"+k.hashCode() + "):" + v + ", "); });

        System.out.println("\nHashMap (2): ");

        hashMap.entrySet().forEach((e) -> {
            System.out.print(e.getKey() + " : " + e.getValue() + ", ");
        });
    }
}

LinkedHashMap (1):

10 (#=10):10, 9 (#=9):9, 8 (#=8):8, 7 (#=7):7, 6 (#=6):6, 5 (#=5):5, 4 (#=4):4, 3 (#=3):3, 2 (#=2):2, 1 (#=1):1, 0 (#=0):0,

LinkedHashMap (2):

10 : 10, 9 : 9, 8 : 8, 7 : 7, 6 : 6, 5 : 5, 4 : 4, 3 : 3, 2 : 2, 1 : 1, 0 : 0,

HashMap (1):

0 (#:0):0, 1 (#:1):1, 2 (#:2):2, 3 (#:3):3, 4 (#:4):4, 5 (#:5):5, 6 (#:6):6, 7 (#:7):7, 8 (#:8):8, 9 (#:9):9, 10 (#:10):10,

HashMap (2):

0 : 0, 1 : 1, 2 : 2, 3 : 3, 4 : 4, 5 : 5, 6 : 6, 7 : 7, 8 : 8, 9 : 9, 10 : 10,

@Utpal Kumar 2017-11-13 03:52:15

There are a lot of ways to do this. Below is a few simple steps:

Suppose you have one Map like:

Map<String, Integer> m = new HashMap<String, Integer>();

Then you can do something like the below to iterate over map elements.

// ********** Using an iterator ****************
Iterator<Entry<String, Integer>> me = m.entrySet().iterator();
while(me.hasNext()){
    Entry<String, Integer> pair = me.next();
    System.out.println(pair.getKey() + ":" + pair.getValue());
}

// *********** Using foreach ************************
for(Entry<String, Integer> me : m.entrySet()){
    System.out.println(me.getKey() + " : " + me.getValue());
}

// *********** Using keySet *****************************
for(String s : m.keySet()){
    System.out.println(s + " : " + m.get(s));
}

// *********** Using keySet and iterator *****************
Iterator<String> me = m.keySet().iterator();
while(me.hasNext()){
    String key = me.next();
    System.out.println(key + " : " + m.get(key));
}

@Tom Hawtin - tackline 2008-09-05 21:26:57

Typical code for iterating over a map is:

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

HashMap is the canonical map implementation and doesn't make guarantees (or though it should not change order if no mutating operation are performed on it). SortedMap will return entries based on the natural ordering of the keys, or a Comparator, if provided. LinkedHashMap will either return entries in insertion-order or access-order depending upon how it has been constructed. EnumMap returns entries in natural order of keys.

(Update: I think this is no longer true.) Note, IdentityHashMap entrySet iterator currently has a peculiar implementation which returns the same Map.Entry instance for every item in the entrySet! However, every time a new the iterator advances the Map.Entry is updated.

@Premraj 2011-03-10 15:41:06

EnumMap also has this peculiar behaviour along with IdentityHashMap

@jpaugh 2016-01-26 20:41:34

"LinkedHashMap will either return entries in [...] access-order [...]" ... so you access the elements in the order you access them? Either tautological, or something interesting which could use a digression. ;-)

@Tom Hawtin - tackline 2016-01-26 21:24:00

@jpaugh Only direct accesses to the LinkedHashMap count. Those through iterator, spliterator, entrySet, etc., do not modify the order.

@Peter Mortensen 2018-02-06 22:36:54

1. thoughif? 2. The last paragraph might benefit from a brush-up.

@Mr. Polywhirl 2015-05-13 12:37:32

Here is a generic type-safe method which can be called to dump any given Map.

import java.util.Iterator;
import java.util.Map;

public class MapUtils {
    static interface ItemCallback<K, V> {
        void handler(K key, V value, Map<K, V> map);
    }

    public static <K, V> void forEach(Map<K, V> map, ItemCallback<K, V> callback) {
        Iterator<Map.Entry<K, V>> it = map.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry<K, V> entry = it.next();

            callback.handler(entry.getKey(), entry.getValue(), map);
        }
    }

    public static <K, V> void printMap(Map<K, V> map) {
        forEach(map, new ItemCallback<K, V>() {
            @Override
            public void handler(K key, V value, Map<K, V> map) {
                System.out.println(key + " = " + value);
            }
        });
    }
}

Example

Here is an example of its use. Notice that the type of the Map is inferred by the method.

import java.util.*;

public class MapPrinter {
    public static void main(String[] args) {
        List<Map<?, ?>> maps = new ArrayList<Map<?, ?>>() {
            private static final long serialVersionUID = 1L;
            {
                add(new LinkedHashMap<String, Integer>() {
                    private static final long serialVersionUID = 1L;
                    {
                        put("One", 0);
                        put("Two", 1);
                        put("Three", 3);
                    }
                });

                add(new LinkedHashMap<String, Object>() {
                    private static final long serialVersionUID = 1L;
                    {
                        put("Object", new Object());
                        put("Integer", new Integer(0));
                        put("Double", new Double(0.0));
                    }
                });
            }
        };

        for (Map<?, ?> map : maps) {
            MapUtils.printMap(map);
            System.out.println();
        }
    }
}

Output

One = 0
Two = 1
Three = 3

Object = [email protected]
Integer = 0
Double = 0.0

@Suresh Atta 2013-03-21 19:33:26

Yes, as many people agreed this is the best way to iterate over a Map.

But there are chances to throw nullpointerexception if the map is null. Don't forget to put null .check in.

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

@pkaeding 2008-09-05 21:15:19

Yes, the order depends on the specific Map implementation.

@ScArcher2 has the more elegant Java 1.5 syntax. In 1.4, I would do something like this:

Iterator entries = myMap.entrySet().iterator();
while (entries.hasNext()) {
  Entry thisEntry = (Entry) entries.next();
  Object key = thisEntry.getKey();
  Object value = thisEntry.getValue();
  // ...
}

@jai 2009-10-20 13:20:05

Prefer for-loop than while.. for(Iterator entries = myMap.entrySet().iterator(); entries.hasNext(); ) {...} With this syntax the 'entries' scope is reduced to the for loop only.

@pkaeding 2012-01-10 15:42:29

@jpredham You are right that using the for construct as for (Entry e : myMap.entrySet) will not allow you to modify the collection, but the example as @HanuAthena mentioned it should work, since it gives you the Iterator in scope. (Unless I'm missing something...)

@JohnK 2015-01-10 00:06:57

IntelliJ is giving me errors on Entry thisEntry = (Entry) entries.next();: doesn't recognize Entry. Is that pseudocode for something else?

@pkaeding 2015-01-14 02:35:45

@JohnK try importing java.util.Map.Entry.

@user5778069 2017-01-21 08:09:19

This solution will not work if you have a integer key and String key.

@George Siggouroglou 2014-08-04 10:30:49

Java 8:

You can use lambda expressions:

myMap.entrySet().stream().forEach((entry) -> {
    Object currentKey = entry.getKey();
    Object currentValue = entry.getValue();
});

For more information, follow this.

@humblerookie 2014-08-21 19:49:06

@injecteer: Seems the motive of lambda expressions

@Holger 2016-11-09 12:37:24

You don’t need a stream if you just want to iterate over a map. myMap.forEach( (currentKey,currentValue) -> /* action */ ); is much more concise.

@Leigh Caldwell 2008-09-05 21:18:00

In theory, the most efficient way will depend on which implementation of Map. The official way to do this is to call map.entrySet(), which returns a set of Map.Entry, each of which contains a key and a value (entry.getKey() and entry.getValue()).

In an idiosyncratic implementation, it might make some difference whether you use map.keySet(), map.entrySet() or something else. But I can't think of a reason why anyone would write it like that. Most likely it makes no difference to performance what you do.

And yes, the order will depend on the implementation - as well as (possibly) the order of insertion and other hard-to-control factors.

[edit] I wrote valueSet() originally but of course entrySet() is actually the answer.

@Rupendra Sharma 2017-04-06 06:36:15

package com.test;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Test {

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("ram", "ayodhya");
        map.put("krishan", "mathura");
        map.put("shiv", "kailash");

        System.out.println("********* Keys *********");
        Set<String> keys = map.keySet();
        for (String key : keys) {
            System.out.println(key);
        }

        System.out.println("********* Values *********");
        Collection<String> values = map.values();
        for (String value : values) {
            System.out.println(value);
        }

        System.out.println("***** Keys and Values (Using for each loop) *****");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("Key: " + entry.getKey() + "\t Value: "
                    + entry.getValue());
        }

        System.out.println("***** Keys and Values (Using while loop) *****");
        Iterator<Entry<String, String>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) entries
                    .next();
            System.out.println("Key: " + entry.getKey() + "\t Value: "
                    + entry.getValue());
        }

        System.out
                .println("** Keys and Values (Using java 8 using lambdas )***");
        map.forEach((k, v) -> System.out
                .println("Key: " + k + "\t value: " + v));
    }
}

@The Coordinator 2013-10-21 10:15:25

In Java 8 you can do it clean and fast using the new lambdas features:

 Map<String,String> map = new HashMap<>();
 map.put("SomeKey", "SomeValue");
 map.forEach( (k,v) -> [do something with key and value] );

 // such as
 map.forEach( (k,v) -> System.out.println("Key: " + k + ": Value: " + v));

The type of k and v will be inferred by the compiler and there is no need to use Map.Entry anymore.

Easy-peasy!

@Vitalii Fedorenko 2014-06-28 12:46:14

Depending on what you want to do with a map, you can also use stream API on the entries returned by map.entrySet().stream() docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.ht‌​ml

@Chris 2017-04-20 20:29:31

This won't work if you want to reference non-final variables declared outside your lambda expression from within the forEach()...

@The Coordinator 2017-04-21 21:44:16

@Chris Correct. It won't work if you try to use effectively non-final variables from outside the lambda.

@Sajad NasiriNezhad 2016-04-13 07:47:46

           //Functional Oprations
            Map<String, String> mapString = new HashMap<>();
            mapString.entrySet().stream().map((entry) -> {
                String mapKey = entry.getKey();
                return entry;
            }).forEach((entry) -> {
                String mapValue = entry.getValue();
            });

            //Intrator
            Map<String, String> mapString = new HashMap<>();
            for (Iterator<Map.Entry<String, String>> it = mapString.entrySet().iterator(); it.hasNext();) {
                Map.Entry<String, String> entry = it.next();
                String mapKey = entry.getKey();
                String mapValue = entry.getValue();
            }

            //Simple for loop
            Map<String, String> mapString = new HashMap<>();
            for (Map.Entry<String, String> entry : mapString.entrySet()) {
                String mapKey = entry.getKey();
                String mapValue = entry.getValue();

            }

@dmunozfer 2013-11-29 12:53:43

If you have a generic untyped Map you can use:

Map map = new HashMap();
for (Map.Entry entry : ((Set<Map.Entry>) map.entrySet())) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}

@Pranoti 2013-07-01 12:54:20

You can do it 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());
}

@Fadid 2014-03-19 17:34:52

    Iterator iterator = map.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry element = (Map.Entry)it.next();
        LOGGER.debug("Key: " + element.getKey());
        LOGGER.debug("value: " + element.getValue());    
    }

@Syd Lambert 2015-10-27 18:09:34

If you want to iterate through the map in the order that the elements were added, use LinkedHashMap as opposed to just Map.

This approach has worked for me in the past:

LinkedHashMap<String,Integer> test=new LinkedHashMap();

test.put("foo",69);
test.put("bar",1337);

for(int i=0;i<test.size();i++){
    System.out.println(test.get(test.keySet().toArray()[i]));
}

Output:

69
1337

@tomaj 2015-08-29 17:11:44

If your reason for iterating trough the Map, is to do an operation on the value and write to a resulting Map. I recommend using the transform-methods in the Google Guava Maps class.

import com.google.common.collect.Maps;

After you have added the Maps to your imports, you can use Maps.transformValues and Maps.transformEntries on your maps, like this:

public void transformMap(){
    Map<String, Integer> map = new HashMap<>();
    map.put("a", 2);
    map.put("b", 4);

    Map<String, Integer> result = Maps.transformValues(map, num -> num * 2);
    result.forEach((key, val) -> print(key, Integer.toString(val)));
    // key=a,value=4
    // key=b,value=8

    Map<String, String> result2 = Maps.transformEntries(map, (key, value) -> value + "[" + key + "]");
    result2.forEach(this::print);
    // key=a,value=2[a]
    // key=b,value=4[b]
}

private void print(String key, String val){
    System.out.println("key=" + key + ",value=" + val);
}

Related Questions

Sponsored Content

9 Answered Questions

[SOLVED] Java Class that implements Map and keeps insertion order?

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

43 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

32 Answered Questions

[SOLVED] When to use LinkedList over ArrayList in Java?

27 Answered Questions

[SOLVED] What is the best way to iterate over a dictionary?

  • 2008-09-26 18:20:06
  • Jake Stewart
  • 1471642 View
  • 2434 Score
  • 27 Answer
  • Tags:   c# dictionary loops

65 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 3903946 View
  • 3361 Score
  • 65 Answer
  • Tags:   java random integer

57 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

9 Answered Questions

[SOLVED] How can I turn a List of Lists into a List in Java 8?

10 Answered Questions

[SOLVED] Iterating over dictionaries using 'for' loops

11 Answered Questions

[SOLVED] Ways to iterate over a list in Java

Sponsored Content