Java Program to Iterate through Elements of HashMap


In this article, we will understand how to iterate through elements of hash-map. Java HashMap is a hash table based implementation of Java's Map interface. It is a collection of key-value pairs.

Below is a demonstration of the same −

Suppose our input is

Run the program

The desired output would be

The elements of the HashMap are:
1 : Java
2 : Python
3 : Scala
4 : Javascript

Algorithm

Step 1 - START
Step 2 - Declare a HashMap namely input_map.
Step 3 - Define the values.
Step 4 - Iterate using a for-loop, use the getKey() and getValue() functions to fetch the key and value associated to the index.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

import java.util.HashMap;
import java.util.Map;
public class Demo {
   public static void main(String[] args){
      System.out.println("Required packages have been imported");
      Map<String, String> input_map = new HashMap<String, String>();
      input_map.put("1", "Java");
      input_map.put("2", "Python");
      input_map.put("3", "Scala");
      input_map.put("4", "Javascript");
      System.out.println("A Hashmap is declared\n");
      System.out.println("The elements of the HashMap are: ");
      for (Map.Entry<String, String> set : input_map.entrySet()) {
         System.out.println(set.getKey() + " : " + set.getValue());
      }
   }
}

Output

Required packages have been imported
A Hashmap is declared

The elements of the HashMap are:
1 : Java
2 : Python
3 : Scala
4 : Javascript

Example 2

Here, we encapsulate the operations into functions exhibiting object oriented programming.

import java.util.HashMap;
import java.util.Map;
public class Demo {
   static void print(Map<String, String> input_map){
      System.out.println("The elements of the HashMap are: ");
      for (Map.Entry<String, String> set : input_map.entrySet()) {
         System.out.println(set.getKey() + " : " + set.getValue());
      }
   }
   public static void main(String[] args){
      System.out.println("Required packages have been imported");
      Map<String, String> input_map = new HashMap<String, String>();
      input_map.put("1", "Java");
      input_map.put("2", "Python");
      input_map.put("3", "Scala");
      input_map.put("4", "Javascript");
      System.out.println("A Hashmap is declared\n");
      print(input_map);
   }
}

Output

Required packages have been imported
A Hashmap is declared

The elements of the HashMap are:
1 : Java
2 : Python
3 : Scala
4 : Javascript

Updated on: 30-Mar-2022

278 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements