Iterate through HashMap

HashMap contains data in (Key, Value) pairs that can be accessed using a different index type. The Map interface is implemented by the HashMap class, which allows us to store keys. Since Java 1.2, hashMap has been a part of the Java collections framework. Internally, it employs a relatively quick hashing technique.

What is a HashMap in Java?

HashMap is a key-value pair storage container. Each key corresponds to a single value.

A HashMap’s keys must be unique. In other programming languages, HashMap is an associative array or a dictionary. HashMaps utilize more memory because each value has a corresponding key. The time it takes to delete and insert data is constant. You can store null values in HashMaps.

In HashMap, an Map.entry represents a key-value pair. HashMap’s entrySet method returns a set view of the map’s mappings. With the keySet method, you can get a list of keys.

Iterate through HashMap in Java examples

The syntax is as follows:

public class HashMap<K, V>
extends AbstractMap<K, V>
implements Map<K,V>, Clonnable, Serial

In this example, we’ll learn how to iterate over the keys, values, and key/value mappings of a Java HashMap. To follow along with this example, you should be familiar with the following Java programming concepts:

  • HashMap in Java
  • for-each loop in Java
  • Iterator Interface in Java

Different Traversal Methods

We can iterate over the key and value pairs that are listed below and detailed as follows:

Methods:

  • Making Use of an Iterator
  • Looping with enhanced (for-each loop)
  • Using the method forEach()
  • Iterating through a HashMap with a for loop

Let’s explore what each of these methods does before we use them to iterate through a map:

  • entrySet() – produces a map collection-view whose items are drawn from the Map. In the entrySet() the key is returned by entry.getKey(), and the value is returned by entry.getValue().
  • keySet() – returns a list of all keys in this map.
  • values() – returns a list of all the values in this map.

Let’s have a look at how these strategies work in practice.

Using an iterator

Iterator is a java.util package interface that is used to iterate across a collection. As a result, there isn’t much to say about iterators, so we’ll propose some Iterator interface methods for traversing HashMap.

  • hm.entrySet() is used to retrieve all of the Map’s key-value pairs. Internally, a set is made up of entries and stores.
  • hm.entrySet().iterator() returns an iterator that functions as a cursor and advances from the set’s first to the last entry.
  • hmIterator.hasNext() returns a boolean if there is a next element in the set.
  • hmIterator.next() -The next element (Map.Entry) from the set is returned via hmIterator.next().
  • mapElement.getKey() is responsible for returning the key of the related Map.
  • mapElement.getValue() is responsible for returning the value of the related Map.

Example: Program for Traversing through the HashMap in Java

Example 1: Using Iterator

// Importing required classes
import java.util.*;

// Main class
class Codeunderscored {

	// 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("Codeunderscored", 54);
		hm.put("A computer portal", 80);
		hm.put("For code", 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);
		}
	}
}

Example 2: Class for iterating HashMaps using an Iterator

// importing java libraries.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;


public class Iterate {
	public static void main(String[] arguments) {
		// creating hash_map.
		Map<Integer, String> hash_map = new HashMap<Integer, String>();
		// inserting value.
		hash_map.put(1, "Code");
		hash_map.put(2, "Underscored");
		// setting up iterator.
		Iterator<Entry<Integer, String>> it = hash_map.entrySet().iterator();
		// iterating every set of entry in the HashMap.
		while (it.hasNext()) {
			Map.Entry<Integer, String> set = (Map.Entry<Integer, String>) it.next();
			System.out.println(set.getKey() + " = " + set.getValue());
		}
	}
}

Example 3: Iterate through HashMap using Iterator ()

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

class Main {
  public static void main(String[] args) {
 
 // create a HashMap
 HashMap<String, String> companies = new HashMap<>();
    companies.put("Google", "Tech");
    companies.put("Microsoft", "Tech");
    companies.put("Air BNB", "Tourism");
    System.out.println("HashMap: " + companies);

    // create an object of Iterator
    Iterator<Entry<String, String>> iterate1 = companies.entrySet().iterator();

    // iterate through key/value mappings
    System.out.print("Entries: ");
    while(iterate1.hasNext()) {
      System.out.print(iterate1.next());
      System.out.print(", ");
    }

    // iterate through keys
    Iterator<String> iterate2 = companies.keySet().iterator();
    System.out.print("\nKeys: ");
    while(iterate2.hasNext()) {
      System.out.print(iterate2.next());
      System.out.print(", ");
    }

    // iterate through values
    Iterator<String> iterate3 = companies.values().iterator();
    System.out.print("\nValues: ");
    while(iterate3.hasNext()) {
      System.out.print(iterate3.next());
      System.out.print(", ");
    }
  }
}

In the example above, we’re iterating through the hash map’s keys, values, and key/value mappings. To iterate across the hashmap, we utilized the Iterator () method.

Here,

hasNext() returns true if the hashmap’s next element exists.

next() – returns the hashmap’s next entry.

Using for-each Loop

Example 1: Program for Traversing through a HashMap in Java
// Using for-each Loop

// Importing required classes
import java.util.*;

// Main class
class Codeunderscored {

	// Main method
	public static void main(String[] args)
	{

		// The HashMap accepts a string and integer
		// These pair Mappings are for subject name and average marks
		HashMap<String, Integer> hm
			= new HashMap<String, Integer>();

		// Adding mappings to HashMap
		// using put() method
		hm.put("Python", 68);
		hm.put("Programming in Java", 48);
		hm.put("Object Oriented Programming", 50);

		// display every element of Map above
		System.out.println(" HashMap Created is:" + hm);

		// show messages
		System.out.println(
			"The state of HashMap after the addition of the bonus marks:");

		//  HashMap Looping
		// Using for-each loop
		for (Map.Entry mapElement : hm.entrySet()) {
			String key = (String)mapElement.getKey();

			// Addition of bonus marks to all subjects
			int value = ((int)mapElement.getValue() + 8);

			// Printing the marks above that correspond to
			// subject names
			System.out.println(key + " : " + value);
		}
	}
}

The forEach() method

HashMap’s forEach() method was first implemented in Java 8. It is used to iterate across the hashmap. At the same time, it is reducing the number of lines of code, as shown below:

Example 1: Program for traversing Through a HashMap in Java

// 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("Python", 68);
		hm.put("Programming in Java", 48);
		hm.put("Object Oriented Programming", 50);

		// 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)));
	}
}

Example 2: Class uses a forEach to iterate through a HashMap

// importing libraries.
import java.util.HashMap;
import java.util.Map;
// class for iterating HashMap.
public class Iterate{
	public static void main(String[] arguments) {
    // creating hash_map.
		Map<Integer, String> hash_map = new HashMap<Integer, String>();
		// inserting sets in the hash_map.
    hash_map.put(1, "Code");
		hash_map.put(2, "Underscored");
    // iterating it using forEach.
		hash_map.forEach((key,value) -> System.out.println(key + " = " + value));
	}
}

Example 3: Iterate through HashMap using the forEach loop

import java.util.HashMap;
import java.util.Map.Entry;

class Main {
  public static void main(String[] args) {

    // Creating a HashMap
    HashMap<String, String> companies = new HashMap<>();
    companies.put("Google", "Tech");
    companies.put("Microsoft", "Tech");
    companies.put("Air BNB", "Tourism");
    System.out.println("HashMap: " + companies);

    // iterating through key/value mappings
    System.out.print("Entries: ");
    for(Entry<String, String> entry: companies.entrySet()) {
      System.out.print(entry);
      System.out.print(", ");
    }

    // iterating through keys
    System.out.print("\nKeys: ");
    for(String key: companies.keySet()) {
      System.out.print(key);
      System.out.print(", ");
    }

    // iterating through values
    System.out.print("\nValues: ");
    for(String value: companies.values()) {
      System.out.print(value);
      System.out.print(", ");
    }
  }
}

We generated a hashmap named companies in the preceding example. Further, we used the forEach loop to iterate through the items of the hashmap in this case. It’s worth noting that we’re iterating through the keys, values, and key/value mappings separately.

  • companies.entrySet() – returns a list of all the entries in a set view.
  • companies.keySet() returns a set view of all critical companies.
  • values() – returns a list of all the values in a set view.

In this example, we used the Map.Entry class. The nested class returns a view of the map.

Iterating through a HashMap with a for loop

hash_map is used in the code below.

The function entrySet() returns a set view of the mapped components. It is now possible to iterate key-value pairs using the getValue() and getKey() operations.

Example: class for iterating HashMap in Java using a for loop

// importing library.
import java.util.HashMap;
import java.util.Map;

public class Iterate {
	public static void main(String[] arguments) {
    // creating HashMap.
		Map<Integer, String> hash_map = new HashMap<Integer, String>();
		// inserting sets.
		hash_map.put(1, "code");
		hash_map.put(2, "underscored");
		// iterating using for loop.
		for (Map.Entry<Integer, String> set : hash_map.entrySet()) {
		    System.out.println(set.getKey() + " = " + set.getValue());
		}
	}
}

Using the Stream API and Lambdas

The Stream API and lambdas have been available in Java since version 8. Next, we’ll look at using these strategies to iterate a map.

Using forEach() and Lambda expressions

This, like so many other things in Java 8, turns out to be far less complicated than the alternatives. We’ll only use the forEach() method for now:

public void usingLambdaToIterate(Map<String, Integer> map) {
    map.forEach((k, v) -> System.out.println((k + ":" + v)));
}

We don’t need to convert a map to a set of entries in this scenario. In fact, we can start here to learn more about lambda expressions. Of course, we may iterate through the map starting with the keys:

public void usingLambdaAndKeys(Map<String, Integer> map) {
    map.keySet().foreach(k -> System.out.println((k + ":" + map.get(k))));
}

Similarly, we can utilize the values() method in the same way:

public void useLambdaToIterateValues(Map<String, Integer> map) {
    map.values().forEach(v -> System.out.println(("value: " + v)));
}

Using Stream API

One of Java 8’s most notable features is the Stream API. You can also use this feature to loop through a Map. A stream is a collection of elements from a source that can be aggregated in sequential and parallel ways. In addition, you can use a collection, IO operation, or array to source data for a stream.

When doing extra Stream processing, the Stream API should be used; otherwise, it’s just a basic forEach() as mentioned above. To demonstrate how the Stream API works, consider the following example:

public void UseStreamAPIteration(Map<String, Integer> map) {
    map.entrySet().stream()
      // ... some other Stream processings
      .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
}

The keySet() and values() methods of the Stream API are similar to the example above.

Example: Using Stream API for HashMap Iteration

package com.codeunderscored;

import java.util.HashMap;

public class CodeHashMapStreamApi {

    public static void main(String[] args) {

        HashMap<String, Integer> hMap = new HashMap<>();
        hMap.put("fruits", 5);
        hMap.put("vegetables", 2);
        hMap.put("laptops", 7);

        hMap.entrySet().stream().forEach(e -> {
            System.out.format("key: %%s, value: %%d%%n", e.getKey(), e.getValue());
        });
    }
}

The example iterates over a HashMap when using the stream API. The entrySet function returns the entry set, and the stream method returns the stream from the entry set. Later, we use forEach to iterate across the stream.

Iteration over an ArrayList-contained HashMap

Lists are also applicable as values in a HashMap. In this situation, we’ll require an extra loop.

package com.codeunderscored;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HashMapList {

    public static void main(String[] args) {
        
        Map<String, List<String>> m = new HashMap<>();

        m.put("colours", Arrays.asList("red", "green", "blue"));
        m.put("sizes", Arrays.asList("small", "medium", "big"));

        for (Map.Entry<String, List<String>> me : m.entrySet()) {
            
            String key = me.getKey();
            List<String> values = me.getValue();
            
            System.out.println("Key: " + key);
            System.out.print("Values: ");
            
            for (String e: values) {
            
                System.out.printf("%%s ", e);
            }
            
            System.out.println();
        }
    }
}

We iterate through a HashMap with ArrayLists as values in this example. For loops, we utilize two.

Map<String, List<String>> m = new HashMap<>();

m.put("colours", Arrays.asList("red", "green", "blue"));
m.put("sizes", Arrays.asList("small", "medium", "big"));

As values, we define a HashMap using ArrayLists.

for (Map.Entry&lt;String, List&lt;String&gt;&gt; me : m.entrySet()) {

We go over the entering set with enhanced for loop. A key string and a list value are assigned to each entry.

String key = me.getKey();

The getKey method is used to obtain the key.

List<String> values = me.getValue();

With getValue, we get the list.

for (String e: values) {

    System.out.printf("%%s ", e);
}

We iterate over the list of values in the inner for loop.

Conclusion

In this article, we’ve looked at the numerous ways to iterate through the map’s items in Java. Simply said, we can use entrySet(), keySet(), or values() to extract the contents of a Map (). Because these are all sets, the iteration principles are the same for all of them. In addition, we also looked at Lambda expressions and the Stream API, which are only available in Java 8 and higher.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *