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. */

More modern alternative

I would recommend to use something like:
for (Object key: hMap.keySet()) {
System.out.println(hMap.get(key));
}
Or even better with a hMap using generics:
for (Map.Entry entry: hMap.entrySet()) {
System.out.println(entry.getValue());
}

Very helpful! Thanks!

Very helpful! Thanks!

hm

why is it not working if i try to work with the values which itsself are objects of another class ?
Collection c = allLendings.values();
Iterator itr = c.iterator();

while(itr.hasNext())
{
String[] date = itr.next().getLend().split(".");
if(date[1] == month)
{
. ....
}
}

Iterator returns object

Hi,

Iterator's next method returns object. So you need to cast it to appropriate class before invoking its method.

Hope this helps.
Thanks.

Post new comment

What is 5 + 71?
To combat spam, please solve the math question above.

Could not find what you are looking for? Search Java Examples




Feel Tired? Read Jokes & Inspirational Stories, Play Games!