3983

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?

3

46 Answers 46

1
2
11

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);
}
1
  • 2
    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
    – michaeak
    Dec 12, 2018 at 12:00
9
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));
    }
}
8

Map.forEach

What about simply using Map::forEach where both the key and the value are passed to your BiConsumer?

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

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 = java.lang.Object@15db9742
Integer = 0
Double = 0.0
7

Since Java 10, you can use local variable inference (a.k.a. "var") to make a lot of the already available answers less bloated. For example:

for (var entry : map.entrySet()) {
    System.out.println(entry.getKey() + " : " + entry.getValue());
}
6

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));
6

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));
}
6

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);
}
6

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

When you iterate a map using the 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));
        }
    }
}
1
  • keySet() is slow
    – edin-m
    Nov 29, 2019 at 3:38
5

You can search for the key and with the help of the key you can find the associated value of the map as the map has unique key, see what happens when the key is duplicated here or here.

Demo map :

Map<String, String> map = new HashMap();
map.put("name", "Name");
map.put("age", "23");
map.put("address", "NP");
map.put("faculty", "BE");
map.put("major", "CS");
map.put("head", "MDK");

To get the key only, you can use map.keySet(); like this :

for (String key : map.keySet()) {
    System.out.println(key);
}

To get value only, you can use map.values(); like this:

for (String value : map.values()) {
    System.out.println(value);
}

To get both the key and its value, you still can use map.keySet(); and get its corresponding value, like this:

// this prints the key + value pair
for (String k : map.keySet()) {
    System.out.println(k + " " + map.get(k) + " ");
}

map.get(key) gives the value pointed by that key.

3

It doesn't quite answer the OP's question, but might be useful to others who find this page:

If you only need the values and not the keys, you can do this:

Map<Ktype, Vtype> myMap = [...];
for (Vtype v: myMap.values()) {
  System.out.println("value: " + v);
}

Ktype, Vtype are pseudocode.

0
3
Map<String, String> map = 
for (Map.Entry<String, String> entry : map.entrySet()) {
    MapKey = entry.getKey() 
    MapValue = entry.getValue();
}
3

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
2

This is the easiest way of doing it I believe...

/* For example, this could be a map object */
Map<String, Integer> MAP = new Map<>();

// Do something like put keys/value pairs into the map, etc...
MAP.put("Denver", 35);
MAP.put("Patriots", 14);

/* Then, simply use a for each loop like this to iterate */
for (Object o : MAP.entrySet()) {
    Map.Entry pair = (Map.Entry) o;
    // Do whatever with the pair here (i.e. pair.getKey(), or pair.getValue();
}
2

I copied the data of a map to another with this code:

HashMap product = (HashMap) shopping_truck.get(i);
HashMap tmp = new HashMap();
for (Iterator it = product.entrySet().iterator(); it.hasNext();) {
    Map.Entry thisEntry = (Map.Entry) it.next();
    tmp.put(thisEntry.getKey(), thisEntry.getValue());
}
0

Past answers are ok but I feel an explanation of each solution and time complexity will go long one to anyone searching for this.

  1. Using entrySet() and for-each loop:

     Map<String, Integer> myMap = new HashMap<>();
     myMap.put("Alice", 25);
     myMap.put("Bob", 30);
     myMap.put("Charlie", 20);
    
     // Using entrySet()
     for (Map.Entry<String, Integer> entry : myMap.entrySet()) {
         String key = entry.getKey();
         Integer value = entry.getValue();
         System.out.println(key + ": " + value);
     }
    

Explanation:

  • myMap.entrySet() returns a set of key-value pairs (Map.Entry objects).
  • The for-each loop iterates directly over these entries. Time Complexity:
  • Best/Average/Worst Case: O(n), where 'n' is the number of entries in the map. This is because it iterates through each entry once.

Overall Complexity:

  • Linear, making it very efficient.
  1. Using entrySet(), Iterator, and while loop:
    Map<String, Integer> myMap = new HashMap<>();
        myMap.put("Alice", 25);
        myMap.put("Bob", 30);
        myMap.put("Charlie", 20);
    // Using Iterator
    Iterator<Map.Entry<String, Integer>> iterator = myMap.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, Integer> entry = iterator.next();
        String key = entry.getKey();
        Integer value = entry.getValue();
        System.out.println(key + ": " + value);
    }

Explanation:

  • myMap.entrySet().iterator() gets an iterator for the entry set.
  • iterator.hasNext() checks if there's another element.
  • iterator.next() gets the next entry and moves the iterator forward.

Time Complexity:

  • Best/Average/Worst Case: O(n), same as the for-each loop.

  • Overall Complexity: Linear. Compared to the earlier code written, this solution gives you the flexibility of using an iterator if you need to remove elements during the iteration safely.

  1. Using Java 8 Lambda function
 Map<String, Integer> myMap = new HashMap<>();
 myMap.put("Alice", 25);
 myMap.put("Bob", 30);
 myMap.put("Charlie", 20);
// Using forEach()
myMap.forEach((key, value) -> System.out.println(key + ": " + value));

Explanation

  • myMap.forEach() takes a lambda expression (a concise function) that's applied to each entry. Here, we simply print the key-value pair. Time Complexity:
  • Best/Average/Worst Case: O(n), the same as the other methods.
  • Overall Complexity: Linear. Provides a more concise syntax if you only need to process elements and don't require an iterator.

Conclusion All of these methods are effectively equally efficient. In most cases, the choice comes down to readability and whether you need the flexibility of an iterator:

  • For-each loop (entrySet): Clean syntax for simple iteration.
  • Iterator: Useful if you might need to remove entries while iterating.
  • forEach(): follows functional-style approach which is concise
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.