How to Iterate HashMap in Java? - GeeksforGeeks

16 Oct, 2021
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: 
Iterate through a HashMap EntrySet using Iterators.Iterate through HashMap KeySet using Iterator.Iterate HashMap using for-each loop.Iterating through a HashMap using Lambda Expressions.Loop through a HashMap using Stream API.
Iterate through a HashMap EntrySet using Iterators.
Iterate through HashMap KeySet using Iterator.
Iterate HashMap using for-each loop.
Iterating through a HashMap using Lambda Expressions.
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.utilimport java.util.HashMap;import java.util.Map; // Class for iterating HashMap using for looppublic 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());        }    }}
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.utilimport 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));    }}
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 packageimport 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());        }    }}
  
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 packageimport java.util.HashMap;import java.util.Map; // Classpublic 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));    }}
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 classpublic 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()));    }}
1 : First
2 : Second
3 : Third
4 : Fourth
 
adnanirshad158
varshagumber28
abhishek0719kadiyan
ruhelaa48
Java-HashMap
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Program to print ASCII Value of a character
Iterate through List in Java