How to Iterate HashMap in Java?
Last Updated :
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.
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());
}
}
}
OutputP = 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));
}
}
OutputP = 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());
}
}
}
Output1 = 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));
}
}
OutputA = 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()));
}
}
Output1 : First
2 : Second
3 : Third
4 : Fourth
Similar Reads
How to Iterate HashSet in Java?
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. It stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code.Methods to Ite
3 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
How to iterate LinkedHashMap in Java?
LinkedHashMap class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted. Th
2 min read
How to Iterate Over a HashSet Without an Iterator in Java?
In Java, we can iterate over a HashSet without using an Iterator. For this, we need two methods. We can directly loop through the elements of the HashSet. In this article, we will discuss the two methods to iterate over a HashSet without using Iterator. Program to Iterate over a HashSet without an I
2 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
Hashing in Java
In hashing there is a hash function that maps keys to some values. But these hashing function may lead to collision that is two or more keys are mapped to same value. Chain hashing avoids collision. The idea is to make each cell of hash table point to a linked list of records that have same hash fun
6 min read
Traverse Through a HashMap in Java
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 fa
4 min read
How to convert a Stream into a Map in Java
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. In this article, the methods to convert a stream into a map is discussed. Method 1: Using Collectors.t
6 min read
How to Get Elements By Index from HashSet in Java?
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. The class does not guarantee the constant order of elements over time but permits the null element. The underlying data structure for HashSet is Hashtable. HashSet also implement
3 min read
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
4 min read