| by Arround The Web | No comments

How to Iterate a HashMap in Java

While maintaining the records in Java, there can be instances where the developer needs to access a particular “HashMap” to utilize or dump it. For instance, re-utilizing a particular set of entries or moving an outdated set of data to junk. In such cases, iterating a HashMap in Java is assistive in accessing the data and managing the memory effectively.

This write-up will discuss the approaches to iterate a “HashMap” in Java.

What is a HashMap in Java?

A “HashMap” stores items in the form of “key-value” pairs and these can be invoked by an index of any other type (e.g., String). It also allows storing the null keys.

How to Iterate a HashMap in Java?

A HashMap in Java can be iterated using the below-given approaches:

Approach 1: Iterate a HashMap in Java Using “for” Loop

The “entrySet()” method gives a set view of all the entries/elements contained in a hashmap. The “getKey()” and “getValue()” methods fetch the key and value from the entry, respectively. These approaches can be applied in combination to firstly access the hashmap and iterate through the accumulated keys and values using the “for” loop.

Syntax

hashmap.entrySet()

In the above syntax, “hashmap” refers to a “HashMap” class object.

Example

Let’s overview the below-provided example:

import java.util.HashMap;

import java.util.Map;

public class Example {

 public static void main(String args[]) {

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

  custom_hashmap.put(1, "Harry");

  custom_hashmap.put(2, "David");

  custom_hashmap.put(3, "Sara");

   for (Map.Entry<Integer, String> set : custom_hashmap.entrySet()) {

    System.out.println(set.getKey() + ": " + set.getValue());

}}

}

In the above-given code:

  • Firstly, create a “HashMap” named “custom_hashmap” such that the key is specified as an “integer” and value as “string” represented in the code as “Map<Integer, String>”.
  • After that, associate the “put()” method with the hashmap to insert the stated values in the form of “key-value” pairs.
  • Now, apply the “for” loop combined with the “entrySet()” method to iterate through the hashmap.
  • Note that the specified “Map.Entry” interface enables the user to work with a map entry.
  • Lastly, apply the “getKey()” and “getValue()” methods to access the allocated keys and values and display them.

Output

In this output, it can be analyzed that the set key-value pairs are iterated upon and displayed.

Approach 2: Iterate a HashMap in Java Using “forEach()” Method

The “forEach()” method is used to apply a particular operation for each element. This method can be implemented to simply iterate through each key-value pair in the “HashMap” and display it.

Syntax

forEach(con<? super E> x)

In the above syntax, this method takes a parameter “x” which corresponds to the action that needs to be performed for each element.

Example

Let’s follow the below-stated code:

import java.util.HashMap;

import java.util.Map;

public class Example {

public static void main(String args[]) {

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

 custom_hashmap.put(1, "Harry");

 custom_hashmap.put(2, "David");

 custom_hashmap.put(3, "Sara");

 custom_hashmap.forEach((key,value) -> System.out.println(key + ": " + value));

}}

In the above illustration:

  • Recall the discussed approaches to create a “HashMap” and allocate the values in the form of “key-value” pairs.
  • Now, associate the “forEach()” method with the created HashMap and display each of the iterated “key-value” pairs on the console.

Output

As you can see that the keys and their corresponding values in the “HashMap” have been iterated.

Approach 3: Iterate a HashMap in Java Using “Iterator” Object

The “Iterator” object is used to loop through the elements one by one, and the “iterator()” method can be utilized to fetch an Iterator. The “hasNext()” method gives “true” if there is a next element contained in the hashmap, and the “next()” method gives the next hashmap element. These approaches can be applied in combination to iterate through the HashMap, check if there is a next key-value pair, and retrieve it.

Syntax

Iterator iter = x.iterator();

In this syntax:

  • x” is a collection object.
  • iter” is of type Iterator interface and corresponds to “x”.

Example

Let’s overview the below-provided example:

import java.util.Iterator;

import java.util.Map.Entry;

import java.util.HashMap;

import java.util.Map;

public class Example {

 public static void main(String args[]) {

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

  custom_hashmap.put(1, "Harry");

  custom_hashmap.put(2, "David");

  custom_hashmap.put(3, "Sara");

  Iterator<Entry<Integer, String>> iter = custom_hashmap.entrySet().iterator();

  while (iter.hasNext()) {

   Map.Entry<Integer, String> assign = (Map.Entry<Integer, String>) iter.next();

   System.out.println(assign.getKey() + ": " + assign.getValue());

}}}

In the above demonstration, apply the following steps:

  • Repeat the discussed methodologies for creating a “HashMap” and allocating the “key-value” pairs.
  • Now, associate the “Iterator” object with the created HashMap and loop through the key-value pairs with the help of the “entrySet()” and “iterator()” methods.
  • Lastly, examine the HashMap by checking the next element via the applied “hasNext()” method. If so, display the next element using the “next()” method.
  • The attached “getKey()” and “getValue()” methods will make sure that the accumulated element is fetched in the form of a “key-value” pair.

Output

The above output signifies that the iteration is done appropriately.

Conclusion

A “HashMap” stores items in “key-value” pairs. It can be iterated with the help of the “for” loop, the “forEach()” method, or the “Iterator” object. The iteration along a HashMap can be done simply, by accessing each key-value pair, or by referring to the next element, respectively. This blog elaborated on the approaches to iterate a HashMap in Java.

Share Button

Source: linuxhint.com

Leave a Reply