×

How to Iterate a HashMap in Java?

Hash-map is a class of Java collections framework which has the functionality to implement the Map interface of Java. It stores the data in key-value pairs and can be accessed by a different type of index. The keys are unique identifiers that are associated with the values of a map. Here, one object is key, also called an index, and the other object associated with the key is called value. When we try to add the duplicate key, it will automatically replace the corresponding key data.

In this tutorial, we will understand how to iterate over a HashMap using different ways.

To use the HashMap class and its methods, we have to import the java.util.HashMap package. The HashMap class implements the Map interface.

In order to iterate a HashMap in Java, we have to understand how to create it first.

The syntax to create a HashMap is as follows:

Map<K, V> hm_name = new HashMap<>();

Here, the hashmap name is hm_name. K is the key type, and V is the type of values.

Example:

Map<Integer, String> hm = new HashMap<>();

In the above example, Integer is the type of keys, and String is the type of values.

How to iterate over a HashMap

There are various ways to iterate over a HashMap in Java. Some of them are listed below:

  1. Using a for loop
  2. Using a for-each loop
  3. Using the Iterator and while loop
  4. Using the lambda expressions
  5. Looping through HashMap using StreamAPI
  1. Using a for loop

By iterating the HashMap using the for loop, we can use the getValue() and getKey() methods. Using the getValue() and getKey() methods, key-value pairs can be iterated.

The entrySet() method of the HashMap class is used to return a set of key-value pairs of the mapped elements.

Given example explains how to iterate a hashmap using the forloop. Here, we have set.getValue() to fetch the value from set and set.getKey() to fetch the key from set.

IterateUsingForLoop.java

 //importing the necessary packages
import java.util.HashMap;
import java.util.Map;
//class to iterate the HashMap
public class IterateUsingForLoop{
    public static void main(String[] args)
    {
        //Creating the HashMap
        Map<Integer, String> hash_map
            = new HashMap<Integer, String>();
        //Inserting elements/sets to the HashMap
hash_map.put(1, "Apple");
hash_map.put(2, "Guava");
hash_map.put(3, "Banana");
hash_map.put(4, "Pineapple");
        //Iterating the HashMap using for loop
        for (Map.Entry<Integer, String>set :
             hash_map.entrySet()) {
            //Printing all elements of a HashMap
            System.out.println(set.getKey() + " = "
                               + set.getValue());
        }
    }
} 

Output:

How to Iterate a HashMap in Java
  • Using a forEach loop

Here, we use the forEach loop to iterate the key-value pair of a HashMap.

Consider the following example to understand how to use a forEach loop to iterate a HashMap.

IterateUsingForEach.java

 //importing the necessary packages
import java.util.HashMap;
import java.util.Map;
//class to iterate the HashMap
public class IterateUsingForEach {
    public static void main(String[] args)
    {
        //Creating the HashMap
        Map<Integer, String> hash_map
            = new HashMap<Integer, String>();
        //Inserting elements/sets to the HashMap
hash_map.put(1, "Rose");
hash_map.put(4, "Sunflower");
hash_map.put(3, "Jasmine");
hash_map.put(2, "Lily");
        //Iterating the HashMap using forEach loop
        hash_map.forEach(
            (key,value) -> System.out.println(key + " = " + value)
            );
    }
} 

Output:

How to Iterate a HashMap in Java
  • Using the Iterator and while loop

The Iterator is an interface used explicitly for iterating the collection elements. Here, we use the iterator() method of the Iterator interface to iterate through the key-value pairs of HashMap.

The hasNext() method returns true if the hashmap has the next element, and the next() method returns the next element of the hashmap.

Lets see the below example to understand how to use iterator() method to iterate a hashmap:

Iteration.java

 //importing the necessary packages
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
//class to iterate the HashMap
public class Iteration {
    public static void main(String[] args)
    {
        //Creating the HashMap
        Map<Character, String> hash_map
            = new HashMap<Character, String>();
        //Inserting elements/sets to the HashMap
hash_map.put('A', "Arial");
hash_map.put('T', "Times New Roman");
hash_map.put('C', "Calibri");
hash_map.put('G', "Georgia");
        //setting the iterator
        Iterator<Entry<Character, String>> it = hash_map.entrySet().iterator();
        //Iterating the HashMap
        while (it.hasNext()) {
            Map.Entry<Character, String> set = (Map.Entry<Character, String>) it.next();
            System.out.println(set.getKey() + " = " + set.getValue());
        }
    }
} 

Output:

How to Iterate a HashMap in Java
  • Using the lambda expressions

The lambda expression is a new feature introduced in Java 8. It is a small block of code, which takes the arguments and returns a value. It is similar to a function; however, it does not require a name, and it can be implemented inside the function body.

The syntax to use lambda expression:

(argument-list) -> {body}

where,

  • argument-list is the list of arguments given to the expression. It can be empty or non-empty.
  • arrow-token links the argument-list and body of lambda expression.
  • body contains statements and expressions for the lambda expression.

Let's consider the below example to understand how to iterate a hashmap using a lambda expression.

IterateUsingLambda.java

 //importing the necessary packages
import java.util.HashMap;
import java.util.Map;
//class to iterate the HashMap
public class IterateUsingLambda {
    public static void main(String[] args)
    {
        //Creating the HashMap
        Map<Character, Integer> hash_map
            = new HashMap<Character, Integer>();
        //Inserting elements to the HashMap
hash_map.put('A', 1);
hash_map.put('T', 20);
hash_map.put('C', 3);
hash_map.put('G', 7);
        //iterating hashmap using lambda expression
        hash_map.forEach(
            (k, v) -> System.out.println(k+ " = " +v)
        ); 
    }
} 

Output:

How to Iterate a HashMap in Java
  • Looping through HashMap using StreamAPI

Iterating the HashMap using StreamAPI requires entrySet().stream() method and forEach loop. Stream API is used to process the collection of objects.

A stream is a sequence of objects with different methods that are pipelined to give the desired result. It does not modify the data structure; it just gives the result based on pipelined methods.

Here, we invoke the entrySet().stream() method  which returns the stream object and the forEach loop loop iterates the elements of entrySet() method.

Consider the below example to understand how to iterate a hashmap using StreamAPI:

IterateUsingStreamAPI.java

 //importing the necessary packages
import java.util.HashMap;
import java.util.Map;
//class to iterate the HashMap
public class IterateUsingStreamAPI {
    public static void main(String[] args)
    {
        //Creating the HashMap
        Map<Integer, String> hash_map
            = new HashMap<Integer, String>();
        //Inserting elements to the HashMap
hash_map.put(4, "Four");
hash_map.put(6, "Six");
hash_map.put(2, "Two");
hash_map.put(9, "Seven");
        //iterating the key-value pairs in HashMap
        hash_map.entrySet().stream().forEach(
            input -> System.out.println(input.getKey() + " = " + input.getValue() )
            );
    }
} 

Output:

How to Iterate a HashMap in Java

In this way, we have learned how to iterate HashMap in Java using different ways like for loop, forEach loop, an Iterator, lambda expressions, and StreamAPI.


Related Topics

Compare Two Times in Java

Definition The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects. Here we have two objects that have to be compared: the...

4 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both...

3 minutes read.

Longest Odd Even Subsequence in Java

In order to solve the Java problem known as the longest odd-even subsequence, one must identify a sequences in a non-negative array having size s that alternately includes odd and...

6 minutes read.

Thread Program in Java

Thread Program in Java Thread program in Java is the continuation of multithreading program in Java. In this topic, we will learn about the usage of threads, race condition in multithreading,...

8 minutes read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.

Upcasting in Java

To know what is Upcasting in Java we should first equip ourselves about what is casting or type casting in Java. Casting The process of providing or replacing a reference variable of...

3 minutes read.

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

All the important string methods in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

How to add 24 Hours to Date in Java?

In this tutorial, we will learn how to add 24 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.