How to Iterate HashMap in Java?


(Key, Value) pairs are used to store data in Java HashMap collections. Although it is unsynchronized, it is comparable to HashTable. As a result, a HashMap can be accessed by numerous threads without encountering any troubles. Despite the fact that HashMap allows for the storage of null keys as well, there can most effective be one null key object and an infinite wide variety of null values. regarding the order of the map, this class gives no guarantees.

To index the value, the key is utilised. We can store unique keys with HashMap. If we try to insert one, the element of the corresponding key will be replaced with a duplicate key.

Do not forget that we should import the java.util.HashMap package to use HashMap.

Methods Used

There are four main methods that you can use for iterating HashMap −

  • Iterate through a HashMap EntrySet with the help of Iterators.

  • Iterate HashMap with the help of a for-each loop and lambda

  • Iterate through HashMap KeySet employing Iterator.

  • Loop through a HashMap with the usage of Stream API.

Method 1: Iterate through a HashMap EntrySet with the help of Iterators

Here we are going for the use of the getValue() and getKey() functions to iterate through a HashMap. Here's an example implementation.

entryset()

The code we explore right here creates a HashMap first, then provides some key-value pairs to it. Subsequently, we iterate via the HashMap the usage of the entrySet() method in a for loop

Algorithm

  • Step 1 − Import the required Java utility classes.

  • Step 2 − Declare a public class named Tutorialspoint.

  • Step 3 − Define the main method with the String[] args parameter.

  • Step 4 − Create a new instance of the HashMap class called foodTable with key and value of type String.

  • Step 5 − Add elements to the foodTable using the put method.

  • Step 6 − Start a loop to iterate over the entries in the foodTable using the entrySet method.

  • Step 7 − Within each iteration, retrieve the current entry using the set variable.

  • Step 8 − Print the key-value pair of the current entry using System.out.println.

  • Step 9 − End the loop, the main method, and the Tutorialspoint class.

Example

import java.util.HashMap;
import java.util.Map;

public class Tutorialspoint{

   public static void main(String[] args){
      Map<String, String> foodTable
      = new HashMap<String, String>();

      // Incorporating elements to the adobe HashMap
      foodTable.put("C", "C Language");
      foodTable.put("R", "Ruby");
      foodTable.put("J", "Java");
      foodTable.put("P", "PHP");

      // Iterating HashMap through for loop
      for (Map.Entry<String, String> set :
      foodTable.entrySet()) {
         System.out.println(set.getKey() + " -> " + set.getValue());
      }
   }
}

Output

P -> PHP
R -> Ruby
C -> C Language
J -> Java

Method 2: Iterate HashMap with the help of a for-each loop and Lambda

We employ lambda expressions in this method, which are accessible in Java since version 8. The operation of a lambda expression on its input parameters produces a value. It is not necessary to turn every key-value pair into an entry set in order to solve this issue using a lambda expression.

forEach()

This program imports the required Java utility classes, builds a HashMap object called "map," adds it with key-value pairs, and then iterates it using the forEach() function. It displays the company name and the matching net worth for each iteration.

Algorithm

  • Step 1 − Start the program execution by importing the required Java utility classes − Map and HashMap.

  • Step 2 − Create a class named "IterationInstance".

  • Step 3 − Inside the "IterationInstance" class, define the "main" method.

  • Step 4 − Create a new HashMap object called "map" to save organization names along with their respective net worth values.

  • Step 5 − Now, you can use the "put" method to incorporate entries to the map.

  • Step 6 − Use the "forEach" method to iterate over the entries in the map.

  • Step 7 − Inside the lambda expression, define the behavior to be executed for each entry: printing the organization name and its net worth.

  • Step 8 − Execute the lambda expression, printing the company name and net worth for each entry in the map.

  • Step 9 − End the program execution.

Example

import java.util.Map;   
import java.util.HashMap;   
public class IterationInstance {   
   public static void main(String[] arg) {   
      Map<String,String> map = new HashMap<String,String>();   
      map.put("Amazon", "$468 billion");   
      map.put("Apple", "$2.5 trillion"); 
      
      //iteration over map with the help of forEach() method  
      map.forEach((k,v) -> System.out.println("Company Name: "+ k + ", Net Value is: " + v));   
   }   
}

Output

Company Name: Apple, Net Value is: $2.5 trillion
Company Name: Amazon, Net Value is: $468 billion

Method 3: Iterate through HashMap KeySet employing Iterator

This time, an iterator can be used. We might also use the Iterator instance generated by using the Map.entrySet().iterator due to the fact HashMap.entrySet() offers a set, which extends the Collection interface.

While()

The code creates a HashMap object and provides key-value pairs to it. It then iterates through the HashMap and prints the key and value of every pair.

Algorithm

  • Step 1 − Import the necessary classes from the Java utility library.

  • Step 2 − The code then creates a HashMap object called intType to store integer keys and string values.

  • Step 3 − The code adds key-value pairs to the HashMap using the put() method.

  • Step 4 − It then creates an iterator by calling the entrySet().iterator() method on the HashMap.

  • Step 5 −The code iterates through the HashMap using a while loop and the hasNext() method of the iterator.

  • Step 6 − It receives the next HashMap entry using the iterator's next() method.

  • Step 7 − This code then retrieves the key and value of each entry using the getKey() and getValue() methods of the Map.Entry object.

  • Step 8 − This code then prints the key and value with the usage of System.out.println() method.

  • Step 9 − Now, repeat steps 5-eight until there are not any extra entries in the HashMap.

Example

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

public class TLP {

   // Main driver method
   public static void main(String[] arguments){

      // Generating Hash map
      Map<Integer, String> intType
      = new HashMap<Integer, String>();

      // Incorporate data(Key-value pairs) into hashmap
      intType.put(11, "Eleven");
      intType.put(12, "Twelve");
      intType.put(13, "Thirteen");
      intType.put(14, "Fourteen");

      // Iterator
      Iterator<Entry<Integer, String> > new_Iterator
      = intType.entrySet().iterator();

      while (new_Iterator.hasNext()) {
         Map.Entry<Integer, String> new_Map
            = (Map.Entry<Integer, String>)
         new_Iterator.next();

         System.out.println(new_Map.getKey() + " = " + new_Map.getValue());
      }
   }
}

Output

11 = Eleven
12 = Twelve
13 = Thirteen
14 = Fourteen

Method 4: Utilising the Stream API to Iterate Through a HashMap

The stream API is an effective tool for processing collections of items. It permits us to perform operations on the data without changing the original data structure.

entrySet().stream()

The code creates a HashMap to store integer keys and corresponding string values. It then adds four key-value pairs to the map and uses stream and forEach to print each key-value pair in the map. The output displays the keys and their corresponding values.

Algorithm

  • Step 1 − Create a HashMap named intType to keep integer keys and corresponding string values.

  • Step 2 − Adding key-value pairs to the intType HashMap

  • Step 3 − Iterate over every entry i.e, key-value pair in the intType HashMap with the usage of the entrySet() function.

  • Step 4 − For every entry, display the key and its corresponding value.

  • Step 5 − Finally, terminate the code.

Example

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

public class TLP {

   public static void main(String[] arguments){
      Map<Integer, String> intType
         = new HashMap<Integer, String>();

      intType.put(1, "Apple");
      intType.put(2, "Cherry");
      intType.put(3, "Banana");
      intType.put(4, "Berries");
      intType.entrySet().stream().forEach(
         input
         -> System.out.println(input.getKey() + " = " + input.getValue())
      );
   }
}

Output

1 = Apple
2 = Cherry
3 = Banana
4 = Berries

Conclusion

Iterating via a HashMap in Java is a common undertaking when operating with key-price pairs. Java HashMap gives several iteration techniques, such as iterators, for-each loops with lambdas, keysets with iterators, and stream API.

Updated on: 18-Oct-2023

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements