--- title: How to Iterate Over a Hashmap in Java? - Scaler Topics description: This article by Scaler Topics discusses the implementation of HashMap. It mainly focuses on the methods to iterate HashMap in Java. author: Nilesh Sinha category: Java --- :::section{.abstract} In Java, Maps cannot be iterated directly using iterators since they are not Collections. There are mainly five ways to iterate over a Map in java. This article explores each method, discussing their pros and cons. Before delving into the different methods, It is important to understand the Map.Entry<K, V> interface. These iteration techniques are applicable to all Map implementations in Java (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.). ::: :::section{.main} ## Iterate over Map.entrySet() Using For-Each Loop We shall now look at the simple use of enhanced-for loop where the concept of **keySet()**, as well as **values()** method, will also be put into use. But initially, it’s important to see how enhanced-for loop works, so go through its syntax and simple implementation. **Syntax:** ```java for(dataType variable_name : Collections | array) { } ``` **Example:** ```java for(String name: prisoners) { System.out.println(name); } ``` We need to mention the data type according to which enhanced-for loop will iterate, it makes the code more understandable. We'll iterate the keys with the help of enhanced-for loop: ```java for(String name: hashMap.keySet()) { } ``` For `entrySet()`, we'll use an enhanced-for loop in this manner: ```java //Map.Entry as a reference to the entrySet elements (key -> value) for(Map.Entry<String, Integer> entry: hashMap.entrySet()) { } ``` Imagine a scenario where we just have to fetch the names of prisoners. It can be done by using **keySet()** in maps. Otherwise, we can use **values()** to fetch the list of all values: ```java import java.util.*; public class Scaler { public static void main(String[] args) { HashMap<String, Integer> hashMap = new HashMap<>(); //Creating hashmap (names -> String, cell number -> Integer) hashMap.put("Boyd Redding", 140); hashMap.put("Andy Dufresne", 142); hashMap.put("Heywood", 146); hashMap.put("Brooks", 145); hashMap.put("Tommy", 148); //We'll iterate hashmap using enhanced-for loop //Iterating keys for(String name: hashMap.keySet()) { //Printing keys and their corresponding values System.out.println(name + ":" + hashMap.get(name)); } //Map.Entry as a reference to the entrySet elements (key -> value) for(Map.Entry<String, Integer> entry: hashMap.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); } } } ``` **Output:** ```plaintext Printing elements with keySet method: Boyd Redding:140 Andy Dufresne:142 Heywood:146 Brooks:145 Tommy:148 Printing elements with entrySet method: Boyd Redding:140 Andy Dufresne:142 Heywood:146 Brooks:145 Tommy:148 ``` ::: :::section{.main} ## Iterate over Keys or Values Using keySet() and values() Methods If it is the collections in Java we’re discussing, the knowledge of **Iterator** is of utmost importance. **Iterator** that can read as well as remove objects but is a unidirectional cursor (works in the forward direction only). It can be used on all Collection objects and is a universal cursor. It is an interface that uses the `iterator()` method available in the Collection interface. **Syntax:** ```java Iterator<E> iterator = c.iterator(); ``` `E` is the data type of the returned element and `c` refers to a Collection object. **Iterator** interface also has four methods, of which we’ll be using these two in our examples. - **hasNext()**: This method returns true if there are more elements in Collections. **Syntax:** ```java boolean hasNext(); ``` - **next()**: This method returns the next element available for iteration. If there isn’t any more element available, it’d throw **NoSuchElementException**. **Syntax:** ```java Object next(); ``` The `hasNext()` method is put as the condition for the while loop which returns true if there are more elements to iterate. Eventually, we would print the elements by calling the next element once in each iteration. ```java while(prisoners.hasNext()) { System.out.print(cells.next() + ", "); } ``` **Here's the final code with iterator()** ```java import java.util.*; public class Scaler { public static void main(String[] args) { //Creating hashmap HashMap<String, Integer> hashMap = new HashMap<>(); //Creating hashmap (names -> String, cell number -> Integer) hashMap.put("Boyd Redding", 140); hashMap.put("Andy Dufresne", 142); hashMap.put("Brooks", 145); hashMap.put("Tommy", 148); //Iterating and printing all the keys (names of prisoners) Iterator<String> prisoners = hashMap.keySet().iterator(); System.out.print("Prisoners: "); while(prisoners.hasNext()) { System.out.print(prisoners.next() + ", "); } //Iterating and printing all the values (cell numbers of prisoners) Iterator<Integer> cells = hashMap.values().iterator(); System.out.print("\nCells: "); while(cells.hasNext()) { System.out.print(cells.next() + ", "); } } } ``` **Output:** ```plaintext Prisoners: Boyd Redding, Andy Dufresne, Heywood, Brooks, Tommy, Cells: 140, 142, 146, 145, 148, ``` The next two methods will also demonstrate the use of Iterator with keySet as well as entrySet. ::: :::section{.main} ## Iterate Using Iterators over Map.Entry<K, V> Using iterators over Map.Entry<K, V> does offer advantages, particularly in scenarios where you need to modify the map while iterating over it. This can be useful when you need to filter or manipulate the map's contents based on certain conditions. Additionally, iterators provide more control over the iteration process compared to for-each loops, allowing you to perform more complex operations if needed. entrySet is the set that comprises all key-value pairs in the map.  **Syntax:** ```java hashMap.entrySet(); ``` Now, there’s another interface that will be used here: **Entry interface**. Since a map is defined as a group of key-value pairs and each pair is referred to as an entry, we usually define Map as a collection of entry objects. The Entry interface consists of a few methods to access all the entry objects. * **K getKey()**: This method would return the key for the indicated entry. If the entry is not present in the map, it will throw **IllegalStateException**.`K` is the corresponding key that would be returned. ```java entry.getKey(); ``` * **V getValue()**: This method would return the value for the indicated map entry. `V` is the value returned by calling this method. ```java entry.getValue(); ``` These entry objects originated from the Entry interface and exist inside the Map interface.   Therefore, we’ll use its nested version by denoting it as Map.Entry interface in our example. The iterator used for entrySet in our example would be: ```java import java.util.*; public class Scaler { public static void main(String[] args) { //Creating hashmap HashMap<String, Integer> hashMap = new HashMap<>(); //Creating hashmap (names -> String, cell number -> Integer) hashMap.put("Boyd Redding", 140); hashMap.put("Andy Dufresne", 142); hashMap.put("Heywood", 146); hashMap.put("Brooks", 145); hashMap.put("Tommy", 148); //Using Iterator and Map.Entry as a reference to //the entrySet elements (key -> value) Iterator<Map.Entry<String,Integer>> entries = hashMap.entrySet().iterator(); while(entries.hasNext()) { //Typecasting entrySet elements as Map.Entry type Map.Entry<String,Integer> entry = (Map.Entry<String,Integer>) entries.next(); //Printing the elements System.out.println(entry.getKey() + ":" + entry.getValue()); } } } ``` **Output:** ```plaintext Boyd Redding:140 Andy Dufresne:142 Heywood:146 Brooks:145 Tommy:148 ``` ::: :::section{.main} ## Iterate Using forEach() Method This method use forEach() and lambda expression. A lambda expression simply reduces the hassle of writing the entire line of code that contains a method name. Instead, you can simply mention the parameters followed by the expression. And surprisingly, it will work the same as a method. We just need to mention parameters and a lambda expression will help us yield a value. There is an additional example given below to give you a glimpse of the lambda expression. ```java parameter(s) -> expression ``` Moreover, we need to use a forEach loop. **forEach()** is a method to iterate the Collection elements one by one. Its default implementation is present in the Iterable interface. ```java import java.util.ArrayList; public class Scaler { public static void main(String[] args) { //Create an arraylist ArrayList<Integer> array = new ArrayList<>(); for(int i=1; i<=5; i++) { array.add(i); } //Use forEach loop with i as a parameter array.forEach((i) -> System.out.print(i + " ")); } } ``` **Output:** ```plaintext 1 2 3 4 5 ``` Here, the forEach loop will take the (key, value) as a parameter and use it in the expression to print the result. In our case, we'll use: ```java Let us see what our code will look like with the help of lambda expression. ```java= import java.util.*; public class Scaler { public static void main(String[] args) { //Creating hashmap HashMap<String, Integer> hashMap = new HashMap<>(); //Inserting key-value pair hashMap.put("Boyd Redding", 140); hashMap.put("Andy Dufresne", 142); hashMap.put("Heywood", 146); hashMap.put("Brooks", 145); hashMap.put("Tommy", 148); //Using forEach method to iterate and print the elements hashMap.forEach((key, value) -> System.out.println(key + ":" + value)); } } ``` **Output:** ```plaintext Boyd Redding:140 Andy Dufresne:142 Heywood:146 Brooks:145 Tommy:148 ``` ::: :::section{.main} ## Iterate over Keys and Getting Values This approach allows direct access to both keys and values simultaneously, significantly reducing the time complexity compared to accessing values individually. By leveraging this method, you can streamline your code and improve its performance, making it a preferred practice in practical implementations. ```java import java.util.*; public class Scaler { public static void main(String[] args) { //Creating hashmap HashMap<String, String> hashMap = new HashMap<>(); //Inserting key-value pair hashMap.put("Boyd Redding", "Heywood"); hashMap.put("Andy Dufresne", "Brooks"); hashMap.put("Heywood", "Boyd Redding"); hashMap.put("Brooks", "Andy Dufresne"); hashMap.put("Tommy", "Heywood"); for (String name : hashMap.keySet()) { // search for value String val = hashMap.get(name); System.out.println(name + ": " + val); } } } ``` **Output:** ```plaintext Boyd Redding: Heywood Andy Dufresne: Brooks Heywood: Boyd Redding Brooks: Andy Dufresne Tommy: Heywood ``` ::: :::section{.summary} ## Conclusion - In this article, we have seen how to iterate over a map in java. - Maps in java cannot be iterated directly using iterators since they are not Collections. - There are different methods to iterate a map in java as: using iterator(), using Lambda expression, foreach, hasNext() etc. :::