Friday, August 19, 2022

4 Example to Iterate over Map, HashMap, Hashtable or TreeMap in Java

There are multiple ways to iterate, traverse or loop through Map, HashMap, or TreeMap in Java and we are all familiar with either all of those or some of those. But to my surprise, one of my friends was asked in his interview (he has more than 6 years of experience in Java programming) to write code for getting values from HashMap, Hashtable, ConcurrentHashMap, or TreeMap in Java in at least 4 ways. Just like me he was also surprised by this question but written it. I don't know why exactly someone asks this kind of java interview question to a relatively senior java programmer. Though my closest guess is to verify that whether he is still hands-on with coding in java. 

Anyway, that gives me an idea to write this Java tutorial, and there are multiple ways to traverse, iterate or loop on a Map in Java, so remember this because you may also ask this question J.


How to traverse or loop over a Map, HashMap, or TreeMap in Java

In the next section of this Java tutorial, we will see four different ways of looping or iterating over Map in Java and will display each key and value from HashMap. We will use the following the HashMap for our example. You can see that it contains just two mappings, which means only two keys and two values to deal with. 

HashMap<String, String> loans = new HashMap<String, String>();
loans.put<"home loan", "Citibank");
loans.put<"personal loan", "Wells Fargo");

4 Example to Iterate over Map, HashMap, Hashtable or TreeMap in Java


1. Iterating or looping map using Java 5 foreach loop

Here we will use the new foreach loop introduced in JDK5 for iterating over any map in java and using KeySet of the map for getting keys. this will iterate through all values of Map and display key and value together. 

HashMap<String, String> loans = new HashMap<String, String>();
loans.put("home loan", "citibank");
loans.put("personal loan", "Wells Fargo");

for (String key : loans.keySet()) {
   System.out.println("-------------------");
   System.out.println("Iterating or looping map using java5 foreach loop");
   System.out.println("key: " + key + " value: " + loans.get(key));
}

Output:
------------------------------------------------
Iterating or looping map using java5 foreach loop
key: home loan value: Citibank
------------------------------------------------
Iterating or looping map using java5 foreach loop
key: personal loan value: Wells Fargo





2. Iterating Map in Java using KeySet Iterator

In this Example of looping over HashMap in Java we have used Java Iterator instead of for loop, rest are similar to earlier example of looping. One advantage of using Iterator is that it also allows you to remove keys and entries while iterating. I mean you can remove a particular key from the keySet() and entry from the entrySet() to actually delete that key or entry from the Map. 

Set<String> keySet = loans.keySet();
Iterator<String> keySetIterator = keySet.iterator();
while (keySetIterator.hasNext()) {
   System.out.println("--------------------------");
   System.out.println("Iterating Map in Java using KeySet Iterator");
   String key = keySetIterator.next();
   System.out.println("key: " + key + " value: " + loans.get(key));
}

Output:
------------------------------------------------
Iterating Map in Java using KeySet Iterator
key: home loan value: Citibank
------------------------------------------------
Iterating Map in Java using KeySet Iterator
key: personal loan value: Wells Fargo






3. Looping HashMap in Java using EntrySet and Java 5 for loop

In this Example of traversing Map in Java, we have used EntrySet instead of KeySet. EntrySet is a collection of all Map Entries and contains both Key and Value.

Set<Map.Entry<String, String>> entrySet = loans.entrySet();
for (Entry entry : entrySet) {
   System.out.println("-----------------------");
   System.out.println("looping HashMap in Java using EntrySet and java5 for loop");
   System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}

Output:
------------------------------------------------
looping HashMap in Java using EntrySet and java5 for loop
key: home loan value: Citibank
------------------------------------------------
looping HashMap in Java using EntrySet and java5 for loop
key: personal loan value: Wells Fargo







4. Iterating HashMap in Java using EntrySet and Java iterator

looping iterating hashmap java exampleThis is the fourth and last example of a looping Map and here we have used a combination of Iterator and entrySet() method to display all keys and values of a Java Map. This is my favorite and also the fastest way to iterate over HashMap in Java as you don't need to call get() method to get the value. The Map.Entry object already contains both key and value and you can use it.

Set<Map.Entry<String, String>> entrySet1 = loans.entrySet();
Iterator<Entry<String, String>> entrySetIterator = entrySet1.iterator();
while (entrySetIterator.hasNext()) {
   System.out.println("------------------------------------------------");
   System.out.println("Iterating HashMap in Java 
                    using EntrySet and Java iterator");
   Entry entry = entrySetIterator.next();
   System.out.println("key: " + entry.getKey() 
      + " value: " + entry.getValue());
}

Output:
------------------------------------------------
Iterating HashMap in Java using EntrySet and Java iterator
key: home loan value: Citibank
------------------------------------------------
Iterating HashMap in Java using EntrySet and Java iterator
key: personal loan value: Wells Fargo


That’s all about multiple ways of looping over a Map in Java. In this Java tutorial, we have seen exactly 4 examples to iterator over a Java Map like HashMap, TreeMap, Hashtable in a combination of KeySet and EntrySet by using for loop and Iterator. You can choose the way you want but if you want to access both keys and values then iterating using entrySet() is the best and fastest way as you don't need to call the get() method again to retrieve the value.  

While these code example uses HashMap, it will work for all kind of Map like TreeMap, LinkedHashMap, IdentityHashMap and so on because its using generic method of Map interface. The only difference could be Hashtable which uses Enumeration instead of Iterator so where ever I have used Iterator, it may not work for Hashtable but other should work just fine. 


Let me know if you are familiar with any other ways of iterating and getting each key-value from Map in Java.



Java Tutorial you may like:

Top 30 Eclipse Keyboard Shortcuts for Java Programmer

Thanks for reading this article so far, if you like this tutorial then please share it with your friends and colleagues. 

20 comments :

Anonymous said...

Good Examples of iterating hashmap. I think java 5 way of looping hashmap using new for loop is best in terms of cleanliness and readability but Iterator provides in own advantage. as you can remove elements while looping or iterating over hashmap.

Anonymous said...

How to loop through map - use forloop or enhanced for loop.
How to iterate through map - use Iterator
How to loop map in JSP - use JSTL foreach tag

Hino said...

In order to loop HashMap in JSTL you need to include JSTL core library (tag library) and taglib on JSP page.

Bhushan said...

Performance wise best approach:
If you're only interested in the keys, you can iterate through the keySet() of the map:

Map map = ...;

for (String key : map.keySet()) {
// ...
}

If you only need the values, use values():

for (Object value : map.values()) {
// ...
}


Finally, if you want both the key and value, use entrySet():

for (Map.Entry entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}

If you want to remove items mid-iteration, you'll need to do so via an Iterator.

Gorbachau said...

I think using Entry Set along with For loop for traversing Map is the fastest way to iterate. Anyone has, any data to proof this, I just heard and wondering if that is correct or not.

Anonymous said...

Another way is :
Map map = new HashMap();
map.put("1", "2");
for (Iterator itr=map.keySet().iterator();itr.hasNext();){
String next = itr.next();
System.out.println(map.get(next));

}

Ajay Kumar said...

Object[] keyObjectArray = (Object[])map.keySet().toArray();
for(Object key : keyObjectArray){
System.out.println( "Key :"+key+" Value : "+map.get(key));
}

Unknown said...

It is useful to beginners.Plz provide explanation about -"What type of searching algorithm is using while getting key and values from HashMap."
hanks for very detailed explanation.

Gauri said...

Hello Sir, Which one is the best way to iterate over HashMap? I personally think foreach loop using with entry set, what is your opinion?

timhoustontx said...

it's not really 4 ways, just 2. the for loops are using iterators, too.

Unknown said...

hey Javin
I have already mentioned your blog there and this is for just reference in future.
Hope you will not mind

keep writing :)

javin paul said...

Hi Deepak, I understand, but please remove that article, as Google doesn't like duplicate copies. You can keep summary and link to original post.

Anonymous said...

Hello Javin, What is the best way to iterate over Map in Java? Best in terms of performance, robustness and elegant coding?

Virendra said...

Map map=new HashMap();
map.put("E1", "Ram");
map.put("E2", "Ravi");

Enumeration keys = Collections.enumeration(map.keySet());
while( keys.hasMoreElements() ) {
Object key = keys.nextElement();
Object value = map.get(key);
System.out.println(value);
}

Anonymous said...

I think entryset() with iterator is the better way to iterate any kind of abj with respect to key as well as value

Nagendra Gupta said...

Wrong line of code :
for (Entry entry : entrySet) {

Knut W. Hansson said...

Using streams (Java 8) it might look like this (with a simpler print):

HashMap loans = new HashMap();
loans.put("home loan", "citibank");
loans.put("personal loan", "Wells Fargo");

loans.keySet().stream().forEach(key ->
System.out.println("key: " + key + " value: " + loans.get(key)));

javin paul said...

Indeed @Knut, Java 8 makes iterating over Map or List really a one liner, no boiler plate due to imperative nature of Java language any more.

Ralf Hergert said...

Using foreach on Map.Entry can be written shortly as:

for (Map.Entry entry : entrySet) { /* perform something with the entry*/ }

Using this notation the typing for entry (in this case ) is still intact. Which may not bother for the sake of this tutorial, but turns out to be important, when more complex types are about to be processed.

Anonymous said...

for(Entry ent : hasmapObject.enterySet())
{
sop(ent.getKey() +" ===>" +ent.getValue)
}

Post a Comment