How to iterate a Map in Java

Java Map is a key-value pair-based collection that stores data in the form of a key-value pair. Each key in the Map is unique and cannot be duplicated. The value can be accessed using the corresponding key.
Java Map is an interface and has various implementations such as HashMap, LinkedHashMap, TreeMap, and Hashtable. HashMap is the most commonly used implementation of Java Map. To use Java Map, we need to import the Java. util.Map or Java. util.* package. In this article, we will discuss the concept of Java Map and the different ways to iterate over it.

Java Map

Definition

Java Map is an interface in Java that maps keys to values, where each key is unique. It’s a collection that doesn’t allow duplicate keys. It’s used to store and access data elements as key-value pairs.

Types of Java Maps

1. HashMap

  • A HashMap is an implementation of the Map interface that stores keys and their corresponding values in a hash table.
  • It uses the hashCode() method of the keys to store and retrieve values quickly.
  • It doesn’t maintain any order between the elements.
  • Example code snippet for creating and adding elements to a HashMap:
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("First", 2);
hashMap.put("Code", 5);

2. TreeMap

  • A TreeMap is an implementation of the Map interface that stores keys and their corresponding values in a sorted tree structure.
  • It maintains the natural ordering of the elements based on the keys or allows a custom Comparator for sorting.
  • Example code snippet for creating and adding elements to a TreeMap:
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("First", 2);
treeMap.put("Code", 5);

3. LinkedHashMap

  • A LinkedHashMap is an implementation of the Map interface that maintains the insertion order of the elements.
  • It stores keys and their corresponding values in a hash table like HashMap. It also maintains a doubly-linked list of the entries in the order they were inserted.
  • Example code snippet for creating and adding elements to a LinkedHashMap:
Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("First", 2);
linkedHashMap.put("Code", 5);

Ways to Iterate over a Java Map

Using forEach() Method

One of the easiest and most commonly used methods to iterate over a Java Map is the forEach() method. It allows us to loop through all the elements of a Map and perform some operation on each element. Here’s an example code snippet to illustrate this:

import java.util.*;
public class Main{
    public static void main (String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("apple", 2);
        map.put("banana", 3);
        map.put("cherry", 5);
        
        map.forEach((key, value) -> System.out.println(key + " = " + value));
    }
}

Output:

banana = 3
apple = 2
cherry = 5

#IMAGE#

Using Iterator:

To iterate over a Java Map using an Iterator, we first need to convert the Map into a Set using the entrySet() method. This method returns a Set of maps. Entry objects which can be used to iterate over the Map.

Let’s see an example to understand the implementation of Iterator:

import java.util.*;
public class Main{
    public static void main (String[] args) {
        Map<String, Integer> marks = new HashMap<>();
        marks.put("John", 80);
        marks.put("Mike", 90);
        marks.put("Sarah", 85);
        
        Set<Map.Entry<String, Integer>> entrySet = marks.entrySet();
        Iterator<Map.Entry<String, Integer>> iterator = entrySet.iterator();
        
        while(iterator.hasNext()) {
            Map.Entry<String, Integer> entry = iterator.next();
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

Output:

Mike: 90
Sarah: 85
John: 80

Using EntrySet:

To iterate over a Java Map using EntrySet, we first need to use the entrySet() method. This method returns a Set of maps. Entry objects which can be used to iterate over the Map.
Let’s see an example to understand the implementation of EntrySet:

import java.util.*;
public class Main{
    public static void main (String[] args) {
        Map<String, Integer> marks = new HashMap<>();
        marks.put("John", 80);
        marks.put("Mike", 90);
        marks.put("Sarah", 85);
        
        Set<Map.Entry<String, Integer>> entrySet = marks.entrySet();
        
        for(Map.Entry<String, Integer> entry : entrySet) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

Output:

Mike: 90
Sarah: 85
John: 80

Best Practices for Java Map Iteration

Advantages and Disadvantages of Different Methods

1. forEach() Method:

Advantages:

1. It is simple and easy to read and understand.
2. It uses Lambda expressions and eliminates the need to write boilerplate code.

Disadvantages:

1. It is not suitable for modifying or removing elements during iteration.
2. It can only iterate over the values of the map.

2. Iterator:

Advantages:

1. It can be used to modify or remove elements during iteration.
2. It is suitable for traversing a large number of elements.

Disadvantages:

1. It is verbose and requires writing more code than other methods.
2. It is not as easy to read and understand as other methods.

3. EntrySet:

Advantages:

1. It is the most efficient method for iterating over the elements of a map.
2. It allows you to access both the key and value of each element in the map.

Disadvantages:

1. It requires writing more code than other methods.
2. It can be less readable and harder to understand than other methods.

When to Use Each Method Based on Use Cases

1. Use forEach() when:

  • You only need to iterate over the values of the map.
  • You don’t need to modify or remove elements during iteration.
  • You want to write simple and easy-to-read code.

2. Use Iterator when:

  • You need to modify or remove elements during iteration.
  • You want to traverse a large number of elements efficiently.
  • You are willing to write more code to achieve these benefits.

3. Use EntrySet when:

  • You want to access both the key and value of each element in the map.
  • You need to iterate over the elements of the map efficiently.
  • You are willing to write more code to achieve these benefits.

Conclusion

In this article, we have explained the concept of Java Map, its types, and various ways to iterate over it. We covered three different methods, forEach(), Iterator, and EntrySet, with examples. We also discussed the advantages and disadvantages of each method and when to use them based on use cases. When working with Java Maps, it’s important to choose the right method for iteration based on the use case. forEach() is the easiest and most efficient method, but it’s not always the best choice.

When working with large maps or when you need to remove elements while iterating, Iterator or EntrySet may be more suitable. Always consider the use case and choose the best method accordingly. With these best practices, you can effectively iterate over Java Maps and optimize your code.

Leave a Reply

Your email address will not be published. Required fields are marked *