Traverse Through a HashMap in Java
Last Updated :
19 Jul, 2022
HashMap stores the data in (Key, Value) pairs, and you can access them by an index of another type. HashMap class implements Map interface which allows us to store key. hashMap is a part of the java collections framework been up since Java 1.2. It internally uses hashing technique which is pretty fast.

Syntax:
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Clonnable, Serial
Different Ways of Traversal
We can iterate over mapping that is key and value pairs a was listed below that are later described as follows:
Methods:
- Using an Iterator
- Using enhanced for Loop (for-each loop)
- Using forEach() Method
Method 1: Using an Iterator
Iterator is an interface in java.util package which is used to iterate through a collection. As such there is nothing special to discuss iterators so do we will be proposing out methods of Iterator interface been used to traverse over HashMap.
- hm.entrySet() is used to retrieve all the key-value pairs called Map.Entries and stores internally into a set.
- hm.entrySet().iterator() returns an iterator that acts as a cursor and points at the first element of the set and moves on till the end.
- hmIterator.hasNext() checks for the next element in the set and returns a boolean
- hmIterator.next() returns the next element(Map.Entry) from the set.
- mapElement.getKey() returns the key of the associated Map.Entry
- mapElement.getValue() return the value of the associated Map.Entry
Example:
Java
// Java Program to Traverse through HashMap
// Using Iterator
// Importing required classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an Hashmap of string-integer pairs
// It contains student name and their marks
HashMap<String, Integer> hm
= new HashMap<String, Integer>();
// Adding mappings to above HashMap
// using put() method
hm.put("GeeksforGeeks", 54);
hm.put("A computer portal", 80);
hm.put("For geeks", 82);
// Printing all elements of HashMap
System.out.println("Created hashmap is" + hm);
// Getting an iterator
Iterator hmIterator = hm.entrySet().iterator();
// Display message only
System.out.println(
"HashMap after adding bonus marks:");
// Iterating through Hashmap and
// adding some bonus marks for every student
while (hmIterator.hasNext()) {
Map.Entry mapElement
= (Map.Entry)hmIterator.next();
int marks = ((int)mapElement.getValue() + 10);
// Printing mark corresponding to string entries
System.out.println(mapElement.getKey() + " : "
+ marks);
}
}
}
OutputCreated hashmap is{GeeksforGeeks=54, A computer portal=80, For geeks=82}
HashMap after adding bonus marks:
GeeksforGeeks : 64
A computer portal : 90
For geeks : 92
Method 2: Using for-each Loop
Example:
Java
// Java program for Traversing through HashMap
// Using for-each Loop
// Importing required classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// creating an empty HashMap of string and integer
// pairs Mappings denotes Student name and marks
HashMap<String, Integer> hm
= new HashMap<String, Integer>();
// Adding mappings to HashMap
// using put() method
hm.put("GeeksforGeeks", 54);
hm.put("A computer portal", 80);
hm.put("For geeks", 82);
// Printing all elements of above Map
System.out.println("Created hashmap is" + hm);
// Display message only
System.out.println(
"HashMap after adding bonus marks:");
// Looping through the HashMap
// Using for-each loop
for (Map.Entry<String,Integer> mapElement : hm.entrySet()) {
String key = mapElement.getKey();
// Adding some bonus marks to all the students
int value = (mapElement.getValue() + 10);
// Printing above marks corresponding to
// students names
System.out.println(key + " : " + value);
}
}
}
Output: Created hashmap is{GeeksforGeeks=54, A computer portal=80, For geeks=82}
HashMap after adding bonus marks:
GeeksforGeeks : 64
A computer portal : 90
For geeks : 92
Method 3: Using forEach() method
forEach() is a method of HashMap that is introduced in java 8. It is used to iterate through the hashmap and also reduces the number of lines of code as proposed below as follows:
Example:
Java
// Java program for traversing Through HashMap
// Using forEach() Method
// Importing required classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty HashMap of string-integer
// pairs
HashMap<String, Integer> hm
= new HashMap<String, Integer>();
// Adding mappings to HashMap
// using put() method
hm.put("GeeksforGeeks", 54);
hm.put("A computer portal", 80);
hm.put("For geeks", 82);
// Printing all elements of above HashMap
System.out.println("Created hashmap is" + hm);
// Display message only
System.out.println(
"HashMap after adding bonus marks:");
// Looping through HashMap and adding bonus marks
// using HashMap.forEach()
hm.forEach((k, v)
-> System.out.println(k + " : "
+ (v + 10)));
}
}
Output: Created hashmap is{GeeksforGeeks=54, A computer portal=80, For geeks=82}
HashMap after adding bonus marks:
GeeksforGeeks : 64
A computer portal : 90
For geeks : 92
Similar Reads
Program to Convert HashMap to TreeMap in Java HashMap is a part of Javaâs collection since Java 1.2. It provides the basic implementation of Map interface of Java which stores the data in (Key, Value) pairs. To access a value in HashMap, one must know its key. HashMap is known as HashMap because it uses a technique Hashing for storage of data.
6 min read
How to Iterate Through HashTable in Java? HashTable is an underlying data structure where the insertion order in HashTable is not preserved, and it is based on the hashcode of keys. Duplicates keys are not allowed, but values can be duplicated. Heterogeneous objects are allowed for both keys and values. Value null is not allowed for both ke
8 min read
Creating HashMap from Other Maps in Java Map interface present in java.util package represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface. Therefore, it behaves a bit differently from the rest of the collection types. A map contains unique keys. There are three main types of maps in
3 min read
Java Program to Implement ConcurrentHashMap API ConcurrentHashMap class obeys the same functional specification as HashTable and includes all the versions of methods corresponding to each method of a HashTable. A HashTable supports the full concurrency of retrievals and adjustable concurrency for updates. All the operations of ConcurrentHashMap a
6 min read
How does HashMap forEach() Method Work in Java 8? The HashMap is a part of collections in the java.util package. The HashMap in Java stores the data in the form of a key-value pair. The HashMap takes the generic parameters for the key along with the value. Similarly, like we instantiate the classes in Java we also instantiate the hash map like we c
3 min read
How to Iterate HashMap in Java? 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 wil
5 min read
Convert HashMap to LinkedList 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. LinkedList is a part of the Collection framework present in java.util package. This class is an implementa
2 min read
Getting Set View of Keys from HashMap in Java The HashMap class of Java provides the functionality of the hash table data structure. This class is found in the java.util package. It implements the Map interface. It stores elements in (Key, Value) pairs and you can access them by an index of another type (e.g. Integer/String). Here, keys are use
2 min read
Java Program to Sort a HashMap by Keys and Values HashMap<K, V> is a Java Collection and is a part of java.util package. It provides the basic implementation of the Map interface of Java. It stores the data in the form of Key, Value pairs, where the keys must be unique but there is no restriction for values. If we try to insert the duplicate
3 min read
Load Factor in HashMap in Java with Examples HashMap is a class that implements the Map interface of Java Collections Framework. The most important feature of a HashMap is that it has a constant time performance for retrieval and insertion. The two factors that dictate the performance of a HashMap are: Initial CapacityLoad Factor Before we exp
5 min read