How to iterate HashMap in java using foreach loop

map-in-java-key-value

The HashMap class uses a hash table to implement the Map interface. This allows the execution time of basic operations, such as get() and put(), to remain constant even for large sets. HashMap implements Map and extends AbstractMap. It does not add any methods of its own.

Once should note following features of HashMap as compair to other collections.

  • HashMap does not guarantee the order of its elements.The order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator.
  • HashMap is not synchronized, this makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.An equivalently synchronised HashMap can be obtained by: Collections.synchronizedMap(myMap)
  • HashMap allows one null key and any number of null values.
  • HashMap’s subclass LinkedHashMap with predictable iteration order (which is insertion order by default), this implementation differs from HashMap.

Let’s see how we Iterate HashMap using for-each loop in java. I am creating a class Address which is a member variable of User class. Following code shows Address class.

and User class…

Put User objects in HashMap and iterate using for-each loop. First we are converting Map into Set using entrySet() method, foreach loop visit each Entry available and return Entry in every visit.

About the Author

has written 68 posts.

I Love Coding, Analyzing, Designing and doing it the right way. I am obsessed about learn anything new daily and sharing what I have learn each Day. This Blog is journey of my Zeal, going through step by step to the mountain of desire to become prefect. Google Wanna Hire me ?

Copyright © 2017 TechZoo - Technology Blog. All rights reserved.
Proudly powered by WordPress. Developed by 7Tech Solutions