×

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

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.

How to enable java in chrome

The Java module is huge for the Java Runtime Environment (JRE). It permits a program to work with the Java stage to run Java applets. Essentially, each of the undertakings connect...

3 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

Java OCR

In this article, you will be acknowledged about what is a tesseract OCR, how it works, what are its used and advantages and disadvantages. Also, you will be able to...

4 minutes read.

Java Math cbrt() Method

The cbrt() method of Math class returns the cube root of a double value. Syntax: public static double cbrt(double a) Parameters: The parameter ‘a’ represents the value whose cube root is to be determined. Return...

2 minutes read.

Java FileOutputStream

What is FileOutputStream?When we need raw stream data written into a file, we need to look for another option: FileOutputStream. It is used when the file's data is byte-oriented. It comes under...

4 minutes read.

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together...

4 minutes read.

Heap Sort in Java

Heap Sort in JavaHeap sort in Java uses the data structure binary heap, min-heap, or max heap to do the sorting of elements. Since min-heap always gives the minimum element first,...

8 minutes read.

&amp;&amp; Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will...

3 minutes read.

Java String equals() method

equals() method compares two string based on the their content. Syntax public boolean equals(Objects anObject) parameter anObject: Object to be compared with the current String. Returns It returns true when the current String is equivalent to...

1 minute read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

Check whether Java is installed or not

As we know that there are various operating systems, to check whether Java is installed or not in Windows and Mac we use the following ways.           Windows Operating System: There are several...

2 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Hogben Numbers in Java

In this section, we will discover what the Hogben number is and develop Java programs that compute it. Java coding interviews and academic exams typically involve questions about the Hogben...

3 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.