Learn How to Iterate HashMap in Java

Updated on October 21, 2024

Article Outline

In Java, a HashMap is part of the Java Collection framework and provides a convenient way to store key-value pairs. It allows for fast retrieval, insertion, and deletion of elements. However, when accessing the data stored in a HashMap, you can iterate through its entries. This article will explore various methods to iterate over a HashMap.

 

Introduction to HashMap

This is a powerful data structure that is used for storing key-value pairs. This makes it easier to retrieve and manipulate the data stored. It also forms one of the Java Collections frameworks and utilizes a Hash table to achieve average time complexity on operations such as insertion, deletion, and access of order O(1). It is allowed to have one null key and any amount of null values of the HashMap, which opens great opportunities for their usage.

 

However, they don’t preserve the order of the elements; if the order is important, it could be a drawback. They manage collisions- circumstances under which different keys give the same hash value – using chaining or open addressing methods. Some applications incorporating HashMaps include caching, counting, and storing tables and associative arrays, hence qualifying as a general-purpose map.

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Methods of Iterate Over a HashMap

 

There are several ways to iterate through a HashMap.

 

  • Iterate through a HashMap EntrySet using iterators
  • Iterate through a HashMap KeySet using Iterator
  • Iterate HashMap using for-each Loop
  • Iterating through a HashMap using Lambda Expression
  • Loop through a HashMap using Stream API

Method 1: Using a for loop to iterate through a HashMap

In the HashMap using a for loop in Java, you typically use the entrySet() method, which provides a set of key-value pairs. You can access each entry as a Map by using an enhanced for loop. Entry object. It allows you to retrieve and populate both keys with key-value pairs. You can loop through the entries to print each key and its associated value. This method is straightforward and leverages Java’s collection framework to iterate through the HashMap in a clean and readable manner, making it easy to handle the data stored within the map.

 

The following program iterates the HashMap using the loop.

 

Program

 

import java.util.HashMap ; import java.util.Map ; class Main{ public static void main(String args[]){ Map<String,String> ob = new HashMap<String, String>() ; ob.put("A", "Amit") ; ob.put("J","Java") ; ob.put("P", "Python") ; ob.put("H", "Hibernate") ; for(Map.Entry<String,String> set: ob.entrySet()) { System.out.println(set.getKey()+" ="+set.getValue()) ; } } }

Output

P =Python A =Amit H =Hibernate J =Java

Method 2: Using a forEach to iterate through a HashMap

In the second method, the forEach function is used to iterate the key-value pairs.

import java.util.HashMap ; import java.util.Map ; class Main{ public static void main(String args[]){ Map<Character,String> ob = new HashMap<Character,String>() ; ob.put('J', "java") ; ob.put('H', "Hibernate") ; ob.put('P', "Python") ; ob.put('A', "Angular") ; ob.forEach((key,value)-> System.out.println(key+"="+value)); } }

Output

P=Python A=Angular H=Hibernate J=java

Method 3:  Using an iterator to iterate through a HashMap

 

The iterator is being used to iterate each mapped pair in HashMap as shown below in the java program.

import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; public class Main { public static void main(String[] arguments) { Map<Integer, String> intType = new HashMap<Integer, String>(); intType.put(1, "First"); intType.put(2, "Second"); intType.put(3, "Third"); intType.put(4, "Fourth"); Iterator<Entry<Integer, String> > ob = intType.entrySet().iterator(); while (ob.hasNext()) { Map.Entry<Integer, String> new_Map = (Map.Entry<Integer, String>) ob.next(); System.out.println(new_Map.getKey() + " = " + new_Map.getValue()); } } }

Output

1 = First 2 = Second 3 = Third 4 = Fourth

Method 4: Iterating through a HashMap using Lambda Expressions

 

Iterating through a HashMap using lambda expressions in Java is a concise and modern way to access and process the key-value pairs. We can use the forEach method that is available in the Map interface.

 

Program

import java.util.HashMap; import java.util.Map; class HashMapInteration{ public static void main(String[]args){ Map<String,Integer> map = new HashMap<>() ; map.put("Apple",1) ; map.put('Banana',2) ; map.put('Cherry',3) ; map.forEach((key,value)->{ System.out.println("Key"+key+"value"+value) ; }); } }

Output

1 = First 2 = Second 3 = Third 4 = Fourth

Method 5: Loop through a HashMap using Stream API

Using the Stream API in Java, we can also iterate through a HashMap, which provides a functional approach to processing collections. This method allows you to leverage various stream operations like filtering, mapping, and collecting.

 

Program

import java.util.HashMap; import java.util.Map; public class HashMapStreamIteration { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("Apple", 1); map.put("Banana", 2); map.put("Cherry", 3); map.entrySet().stream() .forEach(entry -> { String key = entry.getKey(); Integer value = entry.getValue(); System.out.println("Key: " + key + ", Value: " + value); }); } }

Output

Key: Apple, Value: 1 Key: Cherry, Value: 3 Key: Banana, Value: 2

Conclusion

Iterating through a HashMap in Java can be tailored to your needs using various methods. For optimal performance when accessing both keys and values, entrySet() is recommended. If you only need keys or values, consider keySet() or values(), respectively. For scenarios requiring modification during iteration, an Iterator is the safest choice. Lastly, Java 8  streams offer a functional and succinct way to handle entries. Select the iteration technique that best fits your use case for clarity and efficiency. Want to learn more about Java? Consider pursuing the Certificate Program in Application Development offered by Hero Vired.

FAQs
No, HashMap does not guarantee any specific order of its entries. If you need ordered iteration, consider using LinkedHashMap, which maintains insertion order, or TreeMap, which sorts by keys.
They use a LinkedHashMap instead of a HasMap to preserve the order of insertion during iteration.
HashMap does not support thread safety. If a client requires it to be used in a multi-threaded environment, then the synchronized key is used, or we use ConcurrentHashMap.
If you insert a duplicate key, the new value will overwrite the existing value associated with that key.
Yes, a HashMap allows one null key and multiple null values.

Updated on October 21, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved