Wednesday, 18 June 2014

3 ways of loop or iterate through a Map implementation HashMap or TreeMap in Java

In recent days Collections is becoming a very common area of core java to be asked in interviews. When it comes to Collections in Java Map interface and its implementations like HashMap or TreeMap are the most concentrating areas to be picked by the interviewer. In this particular blog we will see how to loop a Map or how to iterate over a Map in Java. By the end of this tutorial you will be able to answer below mentioned questions.

1) How to loop or iterate over a map in Java
2) How to loop or iterate over a HashMap in Java
3) How to loop or iterate over a TreeMap in Java

How to loop or iterate through a Map in Java

There are 4 most common ways of loop or iterating through a Map implementation in Java, here I am explaining them all one by one:

1) Loop or iterating through a HashMap in Java using Iterator interface.

To iterate through a HashMap or loop a HashMap using Iterator we have to get an Iterator over EntrySet of the targeted HashMap. Than we can iterate or loop the EntrySet to get map values and keys from it, see the example below.

2) Loop or iterating through a HashMap in Java using for loop

Here we have used foreach loop added from JDK5 for iterating over any map in java and using KeySet of map for getting keys. this will iterate through all values of Map and display key and value together.

3) Loop or iterating through a HashMap in Java using key as an Object

This is third and last way of iterating over a hashmap or any other implementation of map interface, we have used key of an Map as Object and used for each type of loop to print key and values from a hashmap.

In this particular blog we came across '3 ways of loop or iterate through a Map implementation HashMap or TreeMap in Java' in upcoming blogs we will see more about 'Maven', 'Spring', 'Java' and other open source technologies.