6 ways to Iterate elements in a HashMap in java with example

There are number of ways to traverse / process all the elements in the Map. Like Hashtable, HashMap and TreeMap does not provide the methods elements() and keys() to return enumeration of the values and keys respectively to process all the elements. But the Map interface provides 3 methods to obtain a collection view (Set or Collection object) of the contents of a map.

1. keySet() – returns a Set object referencing the keys contained in the map.

2. entrySet() – returns a Set object referencing the key / object pairs (an object of type Map.entry) stored in the map .

3. values() – returns a Collection object view of the the values contained in the map.

The above Set or collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.

Now let us see lines to convert Map to Set or Collection object. Once it is converted to Set or Collection object, you can either use iterator() method or enhanced for-loop of java 1.5 to iterate over all the keys or values.

1. Set keys = hm.keySet(); // hashmap keys to Set .

Iterator keyIterator=keys.iterator();

2. Set<Map.Entry<String, String>> es = hm.entrySet(); //key/value pair to Set

Iterator<Map.Entry<String, String>> entrysetIterator = es.iterator();

3. Collection vs = hm.values(); – Values to Collection object.

for ( Object v : vs )

4. Finally Traversing HashMap using Enumeration

final Enumeration<String> e = Collections.enumeration(hm.keySet()); – returns an enumeration over all the keys.

In the following code, you can find 6 ways to iterate / enumerate all the elements (strings) in the the hashmap

package com.javaonline;

import java.util.HashMap;
import java.util.*;
public final class TraverseHashMap
    {
      public static void main( String[] args )
        {
        // create a new HashMap
        final Map<String, String> hm = new HashMap<String, String>(  );
        {
        // adding  key/value pairs  to the HashMap
        hm.put("One", "1");
        hm.put("Two", "2");
        hm.put("Three", "3");
        hm.put("Four", "4");
        hm.put("Five", "5");
        hm.put("Six", "6");
        }

       System.out.println("\nUsing Enhanced for loop in Java 1.5");
       System.out.println("\n-----------------------------------\n");
        System.out.println( "\n1. Loop all the keys in the HashMap returned by  keySet() method \n ");
        for ( String key : hm.keySet() )
            {
            String value = hm.get( key );
            System.out.println("key: " + key + ", value: " + value);
            }

        System.out.println( "\n2. Loop all the values in the HashMap  returned by values() method\n" );
            for ( String value : hm.values() )
            {
                 System.out.println( "value : "+value );
            } 

        System.out.println( "\n3. Loop all the key/value pairs  in the HashMap  returned by entrySet() method\n " );
        for ( Map.Entry<String, String> entry : hm.entrySet() )
            {
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println("key: " + key + ", value: " + value);
            }

       System.out.println("\nUsing Iterator");
       System.out.println("\n--------------\n");
       System.out.println( "\n4. Iterate all the keys  returned by keySet() method\n  ");

           Iterator<String> keysetIterator = hm.keySet().iterator();
            while (keysetIterator.hasNext()) {
                 String key = keysetIterator.next();
                 String value = hm.get( key );
                 System.out.println("key: " + key + ", value: " + value);
             }

       System.out.println( "\n5. Iterate all the key/value pairs  returned by entrySet() method\n " );

       Iterator entrysetIterator= hm.entrySet().iterator();
          while (entrysetIterator.hasNext()) {
             Map.Entry entry = (Map.Entry) entrysetIterator.next();
             System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue());
                      }

       System.out.println( "\n6. Enumerate all the keys  " );

       final Enumeration<String> e = Collections.enumeration(hm.keySet());
       while(e.hasMoreElements())
       	{      String key=e.nextElement();
       		   String value = hm.get( key );
       		   System.out.println("key: " + key + ", value: " + value);
       	}
     }
    }

Output
hashmap iteratehashmap iterate1

 

You may also like

Leave a Reply

Be the First to Comment!