Skip to Content

Iterate through the values of Java LinkedHashMap example

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