The Wayback Machine - https://web.archive.org/web/20240726110514/https://www.geeksforgeeks.org/how-to-iterate-hashmap-in-java/
Open In App

How to Iterate HashMap in Java?

Last Updated : 16 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

HashMap is a part of Java’s collection providing the basic implementation of the Map interface of Java by storing the data in (Key, Value) pairs to access them by an index of another type. One object is listed as a key (index) to another object (value). If you try to insert the duplicate key, it will replace the element of the corresponding key. In order to use this class and its methods, it is necessary to import java.util.HashMap package or its superclass.

There is a numerous number of ways to iterate over HashMap of which 5 are listed as below: 

  1. Iterate through a HashMap EntrySet using Iterators.
  2. Iterate through HashMap KeySet using Iterator.
  3. Iterate HashMap using for-each loop.
  4. Iterating through a HashMap using Lambda Expressions.
  5. Loop through a HashMap using Stream API.

Method 1: Using a for loop to iterate through a HashMap. Iterating a HashMap through a for loop to use getValue() and getKey() functions.

Implementation: In the code given below, entrySet() is used to return a set view of mapped elements. From the code given below:

  • set.getValue() to get value from the set.
  • set.getKey() to get key from the set.

Java




// Java Program to Iterate over HashMap
 
// Importing Map and HashMap classes
// from package names java.util
import java.util.HashMap;
import java.util.Map;
 
// Class for iterating HashMap using for loop
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a HashMap
        Map<String, String> foodTable
            = new HashMap<String, String>();
 
        // Inserting elements to the adobe HashMap
        // Elements- Key value pairs using put() method
        foodTable.put("A", "Angular");
        foodTable.put("J", "Java");
        foodTable.put("P", "Python");
        foodTable.put("H", "Hibernate");
 
        // Iterating HashMap through for loop
        for (Map.Entry<String, String> set :
             foodTable.entrySet()) {
 
            // Printing all elements of a Map
            System.out.println(set.getKey() + " = "
                               + set.getValue());
        }
    }
}


Output

P = Python
A = Angular
H = Hibernate
J = Java

Method 2: Using a forEach to iterate through a HashMap. In the second method, the forEach function to iterate the key-value pairs.

Java




// Java Program to Iterate over HashMap
// Iterating HashMap using forEach
 
// Importing Map and HashMap classes
// from package names java.util
import java.util.HashMap;
import java.util.Map;
 
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating hash map
        Map<Character, String> charType
            = new HashMap<Character, String>();
 
        // Inserting data in the hash map.
        charType.put('J', "Java");
        charType.put('H', "Hibernate");
        charType.put('P', "Python");
        charType.put('A', "Angular");
 
        // Iterating HashMap through forEach and
        // Printing all. elements in a Map
        charType.forEach(
            (key, value)
                -> System.out.println(key + " = " + value));
    }
}


Output

P = Python
A = Angular
H = Hibernate
J = Java

Method 3: Using an iterator to iterate through a HashMap. In this method, iterator is being used to iterate each mapped pair in HashMap as shown in below java program.

Example:

Java




// Java Program to Iterate over HashMap
// Using Iterator
 
// Importing classes from java.util package
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
 
public class GFG {
 
    // Main driver method
    public static void main(String[] arguments)
    {
        // Creating Hash map
        Map<Integer, String> intType
            = new HashMap<Integer, String>();
 
        // Inserting data(Key-value pairs) in hashmap
        intType.put(1, "First");
        intType.put(2, "Second");
        intType.put(3, "Third");
        intType.put(4, "Fourth");
 
        // Iterator
        Iterator<Entry<Integer, String> > new_Iterator
            = intType.entrySet().iterator();
 
        // Iterating every set of entry in the HashMap
        while (new_Iterator.hasNext()) {
            Map.Entry<Integer, String> new_Map
                = (Map.Entry<Integer, String>)
                      new_Iterator.next();
 
            // Displaying HashMap
            System.out.println(new_Map.getKey() + " = "
                               + new_Map.getValue());
        }
    }
}


 
 

Output

1 = First
2 = Second
3 = Third
4 = Fourth

 Method 4: Iterating through a HashMap using Lambda Expressions

A lambda expression is a short block of code that takes in parameters and returns a value.  Lambda expressions are similar to methods, but they do not need a name, and they can be implemented right in the body of a method. The simplest lambda expression contains a single parameter and an expression:

parameter -> expression

Example: 

Java




// Iterating HashMap using Lambda Expressions- forEach()
// Importing Map and HashMap classes
// from java.util package
import java.util.HashMap;
import java.util.Map;
 
// Class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating hash map
        Map<Character, String> charType
            = new HashMap<Character, String>();
 
        // Inserting elements(key-value pairs)
        // in the hash map ( Custom inputs)
        charType.put('A', "Apple");
        charType.put('B', "Basketball");
        charType.put('C', "Cat");
        charType.put('D', "Dog");
 
        // Iterating through forEach and
        // printing the elements
        charType.forEach(
            (key, value)
                -> System.out.println(key + " = " + value));
    }
}


Output

A = Apple
B = Basketball
C = Cat
D = Dog

Method 5: Loop through a HashMap using Stream API

The below example iterates over a HashMap with the help of the stream API. 

Stream API is used to process collections of objects.

Streams don’t change the original data structure, they only provide the result as per the pipelined methods

 Steps :

  • First invoke entrySet().stream() method which inturn returns Stream object.
  • Next forEach method, which iterates the input objects that are in the entrySet(). See the below code.

Example:

Java




// Java Program to Iterate over HashMap
// Loop through a HashMap using Stream API
 
// Importing classes from
// package named 'java.util'
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
 
// HashMap class
public class GFG {
 
    // Main driver method
    public static void main(String[] arguments)
    {
        // Creating hash map
        Map<Integer, String> intType
            = new HashMap<Integer, String>();
 
        // Inserting data(key-value pairs) in HashMap
        // Custom inputs
        intType.put(1, "First");
        intType.put(2, "Second");
        intType.put(3, "Third");
        intType.put(4, "Fourth");
 
        // Iterating every set of entry in the HashMap, and
        // printing all elements of it
        intType.entrySet().stream().forEach(
            input
            -> System.out.println(input.getKey() + " : "
                                  + input.getValue()));
    }
}


Output

1 : First
2 : Second
3 : Third
4 : Fourth

 



Similar Reads

How to Copy One HashMap to Another HashMap in Java?
HashMap is similar to the HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values. This class makes no guarantees as to the order of the map. To use this class and its methods, you need to import java.util.HashMap package or its superclass
4 min read
Converting Integer-String HashMap to String-Array-Integer HashMap in Java
Efficient Conversion of a HashMap&lt;Integer, String&gt; into another HashMap&lt;String, Integer[]&gt; involves organizing integer keys based on their corresponding string values. Here's a concise and efficient Java method to accomplish this transformation, focusing on clear and straightforward implementation. Step-by-Step Implementation of Convers
3 min read
Convert String or String Array to HashMap In Java
Considering a string object that contains the student name and roll number separated by a comma, and each student contains the name and roll number separated by a colon. Now need is to convert the String to a Map object so that each student roll number becomes the key of the HashMap, and the name becomes the value of the HashMap object. In order to
4 min read
HashMap clear() Method in Java
The java.util.HashMap.clear() method in Java is used to clear and remove all of the elements or mappings from a specified HashMap. Syntax: Hash_Map.clear() Parameters: The method does not accept any parameters. Return Value: The method does not return any value. Below programs are used to illustrate the working of java.util.HashMap.clear() Method:
2 min read
HashMap containsKey() Method in Java
The java.util.HashMap.containsKey() method is used to check whether a particular key is being mapped into the HashMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map. Syntax: Hash_Map.containsKey(key_element) Parameters: The method takes just one parameter key_element that refers to the key whos
2 min read
HashMap clone() Method in Java
Let us do clear out the foundation concept of shallow copy and deep copy in java. Shallow repetition is quicker. However, it’s “lazy” it handles pointers and references. Rather than creating a contemporary copy of the particular knowledge the pointer points to, it simply copies over the pointer price. So, each the first and therefore the copy can h
3 min read
HashMap containsValue() Method in Java
The java.util.HashMap.containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the HashMap. It takes the Value as a parameter and returns True if that value is mapped by any of the key in the map. Syntax: Hash_Map.containsValue(Object Value) Parameters: The method takes just one paramete
2 min read
HashMap isEmpty() Method in Java
The java.util.HashMap.isEmpty() method of HashMap class is used to check for the emptiness of the map. The method returns True if no key-value pair or mapping is present in the map else False. Syntax: Hash_Map.isEmpty() Parameters: The method does not take any parameters. Return Value: The method returns boolean true if the map is empty or does not
2 min read
HashMap entrySet() Method in Java
The java.util.HashMap.entrySet() method in Java is used to create a set out of the same elements contained in the hash map. It basically returns a set view of the hash map or we can create a new set and store the map elements into them. Syntax: hash_map.entrySet() Parameters: The method does not take any parameter. Return Value: The method returns
2 min read
HashMap get() Method in Java
The java.util.HashMap.get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key. Syntax: Hash_Map.get(Object key_element) Parameter: The method takes one parameter key_element of object type and refers to the key whose
2 min read
Practice Tags :
three90RightbarBannerImg