Skip to Content

Iterate through the values of Java HashMap example

  1. /*
  2.   Iterate through the values of Java HashMap example
  3.   This Java Example shows how to iterate through the values contained in the
  4.   HashMap object.
  5. */
  6.  
  7. import java.util.Collection;
  8. import java.util.HashMap;
  9. import java.util.Iterator;
  10.  
  11. public class IterateValuesOfHashMapExample {
  12.  
  13.   public static void main(String[] args) {
  14.    
  15.     //create HashMap object
  16.     HashMap hMap = new HashMap();
  17.    
  18.     //add key value pairs to HashMap
  19.     hMap.put("1","One");
  20.     hMap.put("2","Two");
  21.     hMap.put("3","Three");
  22.    
  23.     /*
  24.       get Collection of values contained in HashMap using
  25.       Collection values() method of HashMap class
  26.     */
  27.     Collection c = hMap.values();
  28.    
  29.     //obtain an Iterator for Collection
  30.     Iterator itr = c.iterator();
  31.    
  32.     //iterate through HashMap values iterator
  33.     while(itr.hasNext())
  34.       System.out.println(itr.next());
  35.   }
  36. }
  37.  
  38. /*
  39. Output would be
  40. Three
  41. Two
  42. One
  43. */