How to Iterate over a Map in Java

hands typing on the keyboard, colorful coding words on pink background

How to Iterate over a Map in Java

The Java Map interface, unlike other interfaces, does not implement the Iterable interface. Consequently, a Map cannot be navigated using a for-each style for loop or an iterator. Despite this, a solution exists in the form of a collection-view of the Map. This alternative allows the utilization of either a for loop or an iterator for cycling through the Map.

While learning how to iterate over a Map in Java is essential for effective data manipulation, it’s also valuable to understand Java abstract class variables, as they play a crucial role in the broader landscape of Java programming.

Working with Maps and Map Entries in Java

  • In Java, the Map interface does not implement the Iterable interface. Consequently, we cannot cycle through a map using a for-each style loop, nor can we directly obtain an iterator for a map. However, there is a workaround available – we can obtain a collection-view of a map, which does allow the use of either the for loop or an iterator;
  • To work with individual map entries, we can utilize the Map.Entry interface. The entrySet() method, declared by the Map interface, returns a Set containing the map entries. Each of these set elements is a Map.Entry object.

The Map.Entry interface is generic and is declared as follows:

interface Map.Entry<K, V>

In this declaration, K specifies the type of keys, and V specifies the type of values. This feature provides strong typing support for keys and values when working with map entries in Java.

Map Interface’s Collection View Methods

MethodDescription
entrySet()Returns a Set of map entries (objects of type Map.Entry).
keySet()Returns a Set of keys from the map.
values()Returns a Collection of values from the map.
a phone with word connected on it, programming languages, and tags in the cells

Map.Entry Interface Methods for Map Iteration

MethodDescription
getKey()Returns the key for entry.
getValue()Returns the entry’s value.

Map Iteration Example

hands typing on the laptop keyboard and clicking the mouse, the setting icons, and code on the fond

Java Map Iteration Demo

import java.util.Collection;

import java.util.Iterator;

import java.util.Map;

import java.util.Set;

import java.util.TreeMap;

 

public class MapIterationDemo {

 

        public static void main(String[] args) {

                TreeMap map = new TreeMap();

                map.put(new Integer(103), "CCC");

                map.put(new Integer(105), "EEE");

                map.put(new Integer(102), "BBB");

                map.put(new Integer(101), "AAA");

                map.put(new Integer(104), "DDD");

 

                // Iterate using key

                Set s = map.keySet();

                Iterator itr = s.iterator();

                while (itr.hasNext()) {

                        Integer k = (Integer) itr.next();

                        System.out.println(k);

                        // using key can get value

                        String v = (String) map.get(k);

                        System.out.print(k + "\t" + v + "\n");

                }

 

                // Iterate using values

                Collection c = map.values();

                Iterator itr1 = c.iterator();

                while (itr1.hasNext()) {

                        String name = (String) itr1.next();

                        System.out.println(name);

                }

 

                // iterate using both key and value

                Set s1 = map.entrySet();

                Iterator itr2 = s1.iterator();

                while (itr2.hasNext()) {

                        Map.Entry me = (Map.Entry) itr2.next();

                        Integer k = (Integer) me.getKey();

                        String v = me.getValue().toString();

                        System.out.print(k + "\t" + v + "\n");

                }

        }

}

Output: 

101

101        AAA

102

102        BBB

103

103        CCC

104

104        DDD

105

105        EEE

AAA

BBB

CCC

DDD

EEE

101        AAA

102        BBB

103        CCC

104        DDD

105        EEE

Conclusion

Iterating through a Map in Java may not be straightforward due to its lack of support for the Iterable interface. However, with the understanding of the Map.Entry interface and the collection-view of a Map, you can effectively iterate through the Map using keySet(), values(), and entrySet() methods. Equipped with this knowledge and the example in this guide, you can confidently deal with any Map iteration tasks in Java.