Javaexercise.com

How to traverse/iterate HashMap Elements in Java?

HashMap is one of the important data structures and a part of the Java collections framework. It stores data in the form of key-value pairs. In other words, every object(value) can be referenced using another object(key).

There cannot be any duplicate key in a HashMap, if we try to insert a duplicate key, the value of the original key will be replaced with the new value.

Another point to note here is that HashMap is a class that implements Map interface and is found in java.util package.

In this tutorial, we will talk about how to iterate through a HashMap and which way of iteration is the most efficient one.

When it comes to iterating/ traversing a HashMap in Java, we are faced with one major issue, which is that maps cannot be traversed directly using an iterator because the map interface does not extend to the collection interface.

There are 5 major ways to iterate through a HashMap in Java.

  1. Iterating over keys and searching for values

  2. Iterating using forEach() method

  3. Using Iterators over Map.entry< Key, Value>

  4. Using keySet() and values() method

  5. Iterating over Map.entrySet() using for loop

 

Iterate Over keys and Searching for HashMap values in Java

Here, we used the keySet() and get() methods of HashMap. The keySet() method returns a set of all the keys in the HashMap. Since the returned value is a set, it can be iterated using an iterator. See the example below.

import java.util.*;

public class MyClass {
    public static void main(String args[]) {
        HashMap<Integer , String > students = new HashMap<>();
        
        students.put(1, "Aarya");
        students.put(2, "divyanshu");
        students.put(3, "faizal");
        
        for(int roll_no : students.keySet()){
            System.out.println("Roll Number:" + roll_no + " Name: " +students.get(roll_no));
        }
    }
}

Output:

Roll Number:1 Name: Aarya
Roll Number:2 Name: divyanshu
Roll Number:3 Name: faizal

 

This method is however highly inefficient because for each key in the HashMap the get() method gets called, which in the case of HashMap requires the hashCode() and equals() methods of the key object to be evaluated in order to find the associated value. Even if some Map implementations have internal optimizations that check the objects' identity before the hashCode() and equals() are called. This still leads to some extra work, making this method an inefficient choice.

Iterate HashMap by using forEach() method in Java 8

We can iterate a HashMap by using the forEach() method. It takes a lambda expression as an argument and is a very concise way to iterate items almost in a single statement.

This method was added in Java 8 version. So, if you are working with Java 8 or a higher version then use this.

import java.util.*;

public class MyClass {
    public static void main(String args[]) {
        HashMap<Integer , String > students = new HashMap<>();
        
        students.put(1, "Aarya");
        students.put(2, "divyanshu");
        students.put(3, "faizal");
        
        students.forEach(
            (key,value) -> System.out.println("Roll Numer: " +key+ " Name: " +value));
    }
}

Output:

Roll Numer: 1 Name: Aarya
Roll Numer: 2 Name: divyanshu
Roll Numer: 3 Name: faizal

 

Iterate HashMap Using Iterator and Map.Entry interface in Java

In this example, we used the Iterator interface to collect entryset in Map.Entry and then iterate using the hasNext() method.

This method has an advantage, that we can easily remove a pair during an iteration using the Map.remove() method if required. See the example below.

import java.util.*;

public class MyClass {
    public static void main(String args[]) {
        HashMap<Integer , String > students = new HashMap<>();
        
        students.put(1, "Aarya");
        students.put(2, "divyanshu");
        students.put(3, "faizal");
        students.put(4, "Hardik");
        students.put(5, "Karan");
        students.put(6, "Manish");
        
        Iterator<Map.Entry<Integer, String>> i = students.entrySet().iterator();
        
        while(i.hasNext()){
            Map.Entry<Integer, String> entry = i.next();
            System.out.println("Roll Numer: " +entry.getKey()+ " Name: " +entry.getValue());
        }
    }
}

Output:

Roll Numer: 1 Name: Aarya
Roll Numer: 2 Name: divyanshu
Roll Numer: 3 Name: faizal
Roll Numer: 4 Name: Hardik
Roll Numer: 5 Name: Karan
Roll Numer: 6 Name: Manish

 

Iterate HashMap by using keySet() or values() method in Java

If you want to access the keys or values of a HashMap, you can use Map.keySet() or Map.values() method.

The Map.keySet() method returns a set of all the keys and the Map.values() method returns a collection view of all the values in a HashMap. Since the values returned from the mentioned functions are a Set or a collection framework, they can be iterated using an Iterator.

import java.util.*;

public class MyClass {
    public static void main(String args[]) {
        HashMap<Integer , String > students = new HashMap<>();
        
        students.put(1, "Aarya");
        students.put(2, "divyanshu");
        students.put(3, "faizal");
        students.put(4, "Hardik");
        students.put(5, "Karan");
        students.put(6, "Manish");
        
        //acessing on the keys
        for(int roll_no: students.keySet()){
            System.out.println("Roll Number: " +roll_no);
        }
        
        //accessing all the values
        System.out.println("All values:");        
        for(String name: students.values()){
            System.out.println("Name: " +name);
        }
    }
}

Output:

Roll Number: 1
Roll Number: 2
Roll Number: 3
Roll Number: 4
Roll Number: 5
Roll Number: 6
All values:
Name: Aarya
Name: divyanshu
Name: faizal
Name: Hardik
Name: Karan
Name: Manish

 

Iterate HashMap by using entrySet() and for loop in Java

In this example, we used Map.entrySet() method to get a collection view of the HashMap. It then uses the getKey() and getValue() methods to access the key and value values of all the pairs.

import java.util.*;

public class MyClass {
    public static void main(String args[]) {
        HashMap<Integer , String > students = new HashMap<>();
        
        students.put(1, "Aarya");
        students.put(2, "divyanshu");
        students.put(3, "faizal");
        students.put(4, "Hardik");
        students.put(5, "Karan");
        students.put(6, "Manish");
        
        for(Map.Entry<Integer, String> s : students.entrySet()){
            System.out.println("Roll no: " +s.getKey()+ " Name: " +s.getValue());
        }
    }
}

Output:

Roll no: 1 Name: Aarya
Roll no: 2 Name: divyanshu
Roll no: 3 Name: faizal
Roll no: 4 Name: Hardik
Roll no: 5 Name: Karan
Roll no: 6 Name: Manish

 

This iteration way is the most efficient and most commonly used by programmers. You can also modify the above code to just access the key or value.