۱۳۸۷ دی ۱۶, دوشنبه

How to make an iterator for a Hashmap in Java

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. import java.util.Collection;
  7. import java.util.HashMap;
  8. import java.util.Iterator;
  9. public class IterateValuesOfHashMapExample {
  10. public static void main(String[] args) {
  11. //create HashMap object
  12. HashMap hMap = new HashMap();
  13. //add key value pairs to HashMap
  14. hMap.put("1","One");
  15. hMap.put("2","Two");
  16. hMap.put("3","Three");
  17. /*
  18. get Collection of values contained in HashMap using
  19. Collection values() method of HashMap class
  20. */
  21. Collection c = hMap.values();
  22. //obtain an Iterator for Collection
  23. Iterator itr = c.iterator();
  24. //iterate through HashMap values iterator
  25. while(itr.hasNext())
  26. System.out.println(itr.next());
  27. }
  28. }
  29. /*
  30. Output would be
  31. Three
  32. Two
  33. One
  34. */

هیچ نظری موجود نیست:

ارسال یک نظر